1👍
Ok this is not something i recommend doing, but I’ve have been there when it just has to happen.
class ReferrerSerializer(serializers.ModelSerializer):
class Meta:
model = Emp
fields = ('full_name','mobile','email')
class EnquirySerializer(serializers.ModelSerializer):
class Meta:
model = Enquiry
fields = ('name','mobile','email','products',)
# As the fields doesn't already exist you can 'copy' them into the serializer
EnquirySerializer.base_fields["full_name"] = ReferrerSerializer().fields["full_name"]
# Then in the view we can create another model instance.
# you should use the Serializer or a Form class and not save the data directly to a Emp instance here but i left that out for clarity.
class SomeViewSet(ModelViewSet):
model = Enquiry
# post() should only handle new/create calls, but if you want it more clear you can override create() instead.
def post(self, request, *args, **kwargs):
self.emp_data = {}
self.emp_data["full_name"] = self.request.DATA.pop("full_name")
return super(SomeViewSet, self).post(request, *args, **kwargs)
def pre_save(self, obj):
emp = Emp.objects.create(**self.emp_data)
obj.referred_by_emp = emp
return obj
👤krs
Source:stackexchange.com