【问题标题】:How to dynamically fill a hiddenfield in django-rest-frameowork?如何动态填充 django-rest-framework 中的隐藏字段?
【发布时间】:2021-06-14 17:51:49
【问题描述】:

我有两个模型:-

模型 1Location:

  • 姓名
  • 组织
  • 坐标
  • 地址

模型 2FloorPlan:

  • 姓名
  • 地板
  • location(外键定位模型)
  • 组织

我正在尝试创建一个端点以在 FloorPlan 模型上执行 CRUD 操作

这是我的序列化器和视图函数:-

序列化器.py

class FloorPlanSerializer(ModelSerialzer):
    class Meta:
        model = FloorPlan
        fields = '__all__'

views.py

class FloorPlanListView(ListCreateAPIView):
    queryset = FloorPlan.objects.all()
    serializer_class = FloorPlanSerializer

现在我面临的问题是我想在响应中隐藏 organization 字段,并希望使用 POST 或 PUT/PATCH 请求从 location instance(foreignKey) 中填充其值。

任何人都可以建议我实现这一目标的方法吗?

【问题讨论】:

  • 如果要使用位置的组织字段,为什么还需要 FloorPan 组织字段?
  • 嘿,我想根据Location 字段的组织来填充FloorPlan 模型的organization 字段。

标签: python django api django-rest-framework


【解决方案1】:

我的做法是有 2 个序列化器

class FloorPlanSerializerReader(ModelSerialzer):
    class Meta:
        model = FloorPlan
        exclude = ('location', )

class FloorPlanSerializerWriter(ModelSerialzer):
    class Meta:
        model = FloorPlan
        exclude = '__all__'

然后在您的视图中覆盖 get_serializer_class 以根据方法提供不同的供应

class FloorPlanListView(ListCreateAPIView):
    queryset = FloorPlan.objects.all()

    get_serializer_class(self, *args, **kwargs):
        if self.request.method == 'GET':
            return FloorPlanSerializerReader
        elif self.request.method in ['POST', 'PUT', 'PATCH']:
            return FloorPlanSerializerWriter
        else:
            pass # you should probably throw and error here or handle it however you want

【讨论】:

  • 您好,通过这种方法,组织字段在 HTML 表单中可见。我想完全隐藏这个字段并在后端处理它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-29
  • 1970-01-01
  • 2015-08-24
  • 2019-01-03
  • 2016-09-18
  • 1970-01-01
  • 2021-08-20
相关资源
最近更新 更多