我正在使用Django rest framework 3.2.1,GET
是完美的,但POST
不起作用。
这是模特:
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')
观点:
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时:
{"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
使用:
{"coordinateX":33,"coordinateY":44,"description":"5dfadfasdfsadf5"}
我仍然得到相同的结果。
答案 0 :(得分:0)
序列化程序字段为required by default。
此外,DRF ModelSerializer
(和HyperlinkedModelSerializer
)为所有模型的UniqueTogetherValidator
约束添加了unique_together
个。这隐式地使得约束中的所有字段都必需,对于设置了默认值的字段除外。请参阅doc。
ownerBuilding
仅在序列化程序上读取:
ownerBuilding = serializers.HyperlinkedRelatedField(many=False, \
read_only=True, view_name='building-detail')
但是您没有提供defualt也没有手动设置值,因此该字段被视为空,因此出现错误消息。
删除read_only
或设置默认值。