簡體   English   中英

Django:如何在Django Rest API類基本視圖中保存外鍵對象

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

我有兩個模特

用戶和位置

用戶具有位置的外鍵。 因此,在發布請求時,我如何在序列化器中保存位置對象。 我正在使用類庫視圖。

以下是我的代碼

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM