Django : How do i save foreign key object in django rest api class base view
<p>I 'm having Two models</p>

<p><strong>User &amp; Location</strong></p>

<p>User having foreign key of Location. So at the time of <strong>Post</strong> request how do i save the location object in serializer. I'm using classbase view.</p>

<p>Following is my code</p>

<pre><code>class UserList(ListCreateAPIView):

def create(self, request, *args, **kwargs):
        location_id = self.request.data.get("user_location_id")
        location = Location.objects.get(pk=location_id)
        serializer = self.get_serializer(data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        response = {
                "status" : status.HTTP_201_CREATED,
                "message" : "User Created.",
                "response" : serializer.data
            }
        return Response(response)

class UserSerializer(serializers.ModelSerializer):
        location = LocationSerializer(source='user_location_id')

        class Meta:
            model = UserInfo
            fields = ['user_id','user_firstname', 'user_lastname' ,'user_email','user_dob','user_mobileno','user_image','user_blood_group','user_profession','user_fb_id','user_random_id','location']


class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = ["location_id", "location_name"]
</code></pre>

<p>Use this code :</p>

<pre><code>    def create(self, request, args, *kwargs):
            location_id = self.request.data.get("user_location_id")
            location = Location.objects.get(pk=location_id)
            serializer = self.get_serializer(data=request.data, partial=True)
            serializer.is_valid(raise_exception=True)
            serializer.save(user_location_id=location)
            self.perform_create(serializer)
            response = {
                    "status" : status.HTTP_201_CREATED,
                    "message" : "User Created.",
                    "response" : serializer.data
                }
            return Response(response)
</code></pre>

python django django-rest-framework