相关框架:Django,Django REST框架
在POST
上,一切似乎都很好:返回201 Created
响应,并且应该的JSON表示已经保存到响应正文中的数据库是正确的。< / p>
实际上,Flag
和Product
之间的反向关系尚未建立(请参阅下面的相关模型,序列化工具和视图),而Product.flag
实际上是None
(由DRF序列化为null
。
相关型号:
class Product(models.Model):
...
flag = models.OneToOneField('Flag', null=True, blank=True, related_name='product')
class Flag(models.Model):
...
reasons = ManyToManyField('FlagReason')
severity = models.CharField(...)
notes = models.TextField(...)
...
相关DRF序列化程序:
class FlagSerializer(serializers.ModelSerializer):
class Meta:
model = models.Flag
fields = ('id', 'reasons', 'notes', 'created_timestamp',
'modified_timestamp', 'severity', 'product',)
相关DRF观点:
class FlagListCreate(generics.ListCreateAPIView):
queryset = Flag.objects.all()
serializer_class = FlagSerializer
filter_fields = ('severity',)
POST
请求JSON正文:
{
"product": 1328,
"severity": "mid",
"reasons": [1, 2],
"notes": "Test note",
}
201 Created
对上述POST请求的回复(注意product
pk):
{
"id": 31,
"reasons": [
1,
2
],
"notes": "Test note",
"created_timestamp": "2018-04-30T11:54:50.762054+01:00",
"modified_timestamp": "2018-04-30T11:54:50.762084+01:00",
"severity": "mid",
"product": 1328
}
对GET
请求上述标记的回复(注释product
值为null
):
{
"id": 31,
"reasons": [
1,
2
],
"notes": "Test note",
"created_timestamp": "2018-04-30T11:54:50.762054+01:00",
"modified_timestamp": "2018-04-30T11:54:50.762084+01:00",
"severity": "mid",
"product": null
}