1👍
✅
You are getting this error because when you are saving the serializer
the customer
and employee
are not set on the instance
. Setting these values on the serializer
itself won’t have any effect at all. You have to pass these additional values in the save
method of the serializer
.
Additionally, I would suggest that you override the perform_create
method and not the post
method:
def perform_create(self, serializer):
custid = self.request.data.get("customer_id")
empid = self.request.data.get("employee_id")
serializer.save(
customer=Customer.objects.get(pk=custid),
employee=Employee.objects.get(pk=empid)
)
This is straight from the documentation:
The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.
perform_create(self, serializer)
– Called byCreateModelMixin
when saving a new object instance.
UPDATE on using ModelViewSet
:
You don’t need to use APIView
but you could use ModelViewSet
for different operations e.g. list
, retrieve
, create
etc.
class ProjectViewSet(viewsets.ModelViewSet):
queryset = ProjectDetails.objects.all()
serializer_class = ProjectDetailsSerializer
# now you can add your perform_create here
def perform_create(self, serializer):
custid = self.request.data.get("customer_id")
empid = self.request.data.get("employee_id")
serializer.save(
customer=Customer.objects.get(pk=custid),
employee=Employee.objects.get(pk=empid)
)
👤AKS
Source:stackexchange.com