我有两个模型:-
模型 1 Location
:
模型 2 FloorPlan
:
我正在尝试创建一个端点以在 FloorPlan
模型上执行 CRUD 操作
这是我的序列化器和视图函数:-
serializers.py
class FloorPlanSerializer(ModelSerialzer):
class Meta:
model = FloorPlan
fields = '__all__'
views.py
class FloorPlanListView(ListCreateAPIView):
queryset = FloorPlan.objects.all()
serializer_class = FloorPlanSerializer
现在我面临的问题是我想隐藏响应中的 organization
字段,并想从它的 location
instance(foreignKey) with POST 或 PUT/PATCH 填充它的值请求。
谁能建议我实现这一目标的方法。
答案 0 :(得分:0)
我的做法是有 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