Python Django:如何在Django rest api类基视图中保存外键对象

Python Django:如何在Django rest api类基视图中保存外键对象,python,django,django-rest-framework,Python,Django,Django Rest Framework,我有两个模特 用户和位置 具有位置外键的用户。因此,在发布请求时,如何在序列化程序中保存位置对象。我正在使用classbase视图 下面是我的代码 class UserList(ListCreateAPIView): def create(self, request, *args, **kwargs): location_id = self.request.data.get("user_location_id") location = Location.obje

我有两个模特

用户和位置

具有位置外键的用户。因此,在发布请求时,如何在序列化程序中保存位置对象。我正在使用classbase视图

下面是我的代码

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"]
使用此代码:

    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)