[英]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"]
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.