Post to Django rest framework API but always get a

2019-08-06 03:41发布

问题:

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

This is the Model:

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)

The Serializer:

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')

The View:

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

When I test the POST to this API with data:

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

I always get this error:

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

anyone could help?

the http://rest.xxxxxxxx.xyz:8090/buildings/1/ exists.

[edit0]: if I POST with:

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

I still get the same result.

回答1:

Serializer fields are required by default.

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 is read only on the serializer:

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

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

Either remove the read_only or set a default.