gpt4 book ai didi

Django-rest-framework 序列化程序无法保存模型实例

转载 作者:行者123 更新时间:2023-12-01 15:30:10 25 4
gpt4 key购买 nike

我正在使用 DRF。我的模型.py:

class Farm(models.Model):
farmer = models.ForeignKey(User, verbose_name="Farmer of this farm")
name = models.CharField(max_length=15, blank=False, verbose_name="Farm name", help_text="Please give a single word name for your farm.")
address = models.TextField(help_text="Please provide the address without the postal code", blank=False,)
postal_code = models.CharField(max_length=5, blank=False, default='12043')
size = models.DecimalField(max_digits=9, decimal_places=6, blank=False, )

#To add user's full name in the admin interface for better readability
def get_farmer_full_name(self):
return self.farmer.get_full_name()

#Works like a verbose_name but for a method
get_farmer_full_name.short_description = 'Farmers full name'

我的序列化器.py:

class FarmSerializer(serializers.ModelSerializer):

class Meta:
model = Farm
fields = ('farmer', 'name', 'address', 'postal_code', 'size')

def create(self, validated_data):
return Farm.objects.create(**validated_data)

def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.address = validated_data.get('address', instance.address)
instance.postal_code = validated_data.get('postal_code', instance.postal_code)
instance.size = validated_data.get('size', instance.size)
instance.save()
return instance

我的观点.py:

@api_view(('POST',))
def addFarm(request):
data = JSONParser().parse(request)
farmer = Farm(farmer = request.user)
serializer = FarmSerializer(farmer, data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

当我点击 url(r'^farms/save/$', views.addFarm), 这个 url 时,我想用请求中提供的参数保存一个新的 Farm 实例。我正在使用 Postman 发送请求。

但是我得到 {"farmer":["This field is required."],"name":["This field is required."],"address":["This field is required."],"size":["This field is required."]} 错误作为响应。

我的请求如下所示:

enter image description here

注意: 第一个字段 'farmer' 我不能作为参数发送,但我想我必须用 request.user.id< 提取它 并专门传递它,但我不确定。

我做错了什么?如何解决?

最佳答案

在 views.py 中更改它

data = {"farmer": request.user.id}
data.update(request.data)
serializer = FarmSerializer(data=data)

或者根据您的EDIT

data = JSONParser().parse(request)
data.update({"farmer": request.user.id})
serializer = FarmSerializer(data=data)

关于Django-rest-framework 序列化程序无法保存模型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37835730/

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