Pinank Lakhani Pinank Lakhani - 2 months ago 20
Python Question

Django : How do i save foreign key object in django rest api class base view

I 'm having Two models

User & Location

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

Following is my 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"]

Answer

Use this 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)
Comments