Reputation: 401
I have two model's as:-
Model 1 Location
:
Model 2 FloorPlan
:
I am trying to create an endpoint for performing CRUD operation on the FloorPlan
Model
Here is my serializer & view function:-
serializers.py
class FloorPlanSerializer(ModelSerialzer):
class Meta:
model = FloorPlan
fields = '__all__'
views.py
class FloorPlanListView(ListCreateAPIView):
queryset = FloorPlan.objects.all()
serializer_class = FloorPlanSerializer
Now the problem I am facing is I want to hide the organization
field in the response, and would like to fill its value, from it's location
instance(foreignKey) with POST or PUT/PATCH requests.
Can anyone suggest me a way to achieve this.
Upvotes: 0
Views: 85
Reputation: 4459
The way I'd do it is have 2 serializers
class FloorPlanSerializerReader(ModelSerialzer):
class Meta:
model = FloorPlan
exclude = ('location', )
class FloorPlanSerializerWriter(ModelSerialzer):
class Meta:
model = FloorPlan
exclude = '__all__'
and then in your views override get_serializer_class
to have different ones supplies depending on the method
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
Upvotes: 0