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

时间:2016-06-15 12:39:18

标签: django django-rest-framework

我正在使用DRF。 我的models.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'

我的serializers.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 

我的views.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),此网址时,我想使用请求中提供的参数保存新的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

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

我做错了什么?如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

在views.py中更改此内容

$request->user()->id

或根据您的编辑

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