为什么这个OneToOneField反向关系不会持久存储到数据库中?

时间:2018-04-30 11:37:10

标签: django django-rest-framework

相关框架:Django,Django REST框架

POST上,一切似乎都很好:返回201 Created响应,并且应该的JSON表示已经保存到响应正文中的数据库是正确的。< / p>

实际上,FlagProduct之间的反向关系尚未建立(请参阅下面的相关模型,序列化工具和视图),而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
}

0 个答案:

没有答案