gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:42:14 25 4
gpt4 key购买 nike

我有两个模型

用户和位置

具有位置外键的用户。因此,在 Post 请求时,如何将位置对象保存在序列化器中。我正在使用类库 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)

关于python - Django : How do i save foreign key object in django rest api class base view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39394816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com