发布到Django休息框架API,但总是得到一个“这个字段是必需的”错误 [英] Post to Django rest framework API but always get a 'This field is required' error

查看:218
本文介绍了发布到Django休息框架API,但总是得到一个“这个字段是必需的”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django休息框架3.2.1, GET 是完美的,但 POST 不工作

I'm using Django rest framework 3.2.1, the GET is perfect, but POST does not work.

这是模型:

class Sample(models.Model):
    ownerBuilding = models.ForeignKey(Building)
    coordinateX = models.IntegerField(default=0, help_text='X coordinate for this sampling point located in a building')
    coordinateY = models.IntegerField(default=0, help_text='Y coordinate for this sampling point located in a building')
    creation_Time = models.DateTimeField(auto_now_add=True)
    description = models.TextField(null=True,
                               help_text='additional description for this sample point.')

class Meta:
    unique_together = ('ownerBuilding', 'coordinateX','coordinateY')

def __str__(self):
    return "Sample for building " + str(self.ownerBuilding)

序列化器:

class SampleSerializer(serializers.HyperlinkedModelSerializer):
    ownerBuilding = serializers.HyperlinkedRelatedField(many=False, read_only=True, view_name='building-detail')

class Meta:
    model = Sample
    fields = ('url', 'ownerBuilding', 'coordinateX', 'coordinateY', 'creation_Time','description')

查看:

class SampleList(generics.ListCreateAPIView):
    queryset = Sample.objects.all()
    serializer_class = SampleSerializer
    permission_classes = (permissions.IsAuthenticated, IsTechniciansGroupOrReadOnly,)

    def get_queryset(self):
        queryset = Sample.objects.all()
        ownerBuildingId = self.request.query_params.get('ownerBuildingId', None)

        if ownerBuildingId is not None:
            queryset = queryset.filter(ownerBuilding=ownerBuildingId)

        return queryset

当我将 POST 具有数据的API:

When I test the POST to this API with data:

{"ownerBuilding":"http://rest.xxxxxxxx.xyz:8090/buildings/1/","coordinateX":33,"coordinateY":44,"description":"5dfadfasdfsadf5"}

我总是得到这个错误:

{
    "ownerBuilding": [
        "This field is required."
    ]
}

任何人都可以帮助?

http://rest.xxxxxxxx.xyz:8090/buildings/1/ 存在。

[edit0]:
如果我 POST 与:

[edit0]: if I POST with:

{"coordinateX":33,"coordinateY":44,"description":"5dfadfasdfsadf5"}

我仍然得到相同的结果。

I still get the same result.

推荐答案

序列化器字段是默认情况下需要

另外,DRF ModelSerializer (和 HyperlinkedModelSerializer )添加 UniqueTogetherValidator s所有模型的 unique_together 约束。这隐含地使得约束中的所有字段都需要,除了设置了默认值的字段之外。请参阅文档

Also, DRF ModelSerializer (and HyperlinkedModelSerializer) adds UniqueTogetherValidators for all model's unique_together constraints. This implicitly makes all fields in the constraint required, with exception for fields for which defaults are set. See doc.

ownerBuilding 只能在序列化器上阅读:

ownerBuilding is read only on the serializer:

ownerBuilding = serializers.HyperlinkedRelatedField(many=False, \
                            read_only=True, view_name='building-detail')

,但是您不提供defualt或手动设置值,因此该字段被视为空,因此出现错误消息。

but you don't provide a defualt nor set the value manually, so this field is treated as empty, hence the error message.

删除 read_only 或设置默认值。

这篇关于发布到Django休息框架API,但总是得到一个“这个字段是必需的”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆