1

我想在我的数据库中保存一个“反馈”对象的实例,反馈对象有一个“客户”的外键和一个通用的外键,因为它可以与“供应商”或“商店”相关,我制作了 2 个允许POST,一个为供应商创建反馈,另一个为商店创建反馈,都接收主键。

类图示例: 类图

这是我的方法:

@api_view(['POST'])
def store_feedback_view(request, store_id):
    serializer = FeedbackSerializer(data=request.DATA)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

序列化程序是有效的,但是在尝试保存时给我以下错误:

NOT NULL constraint failed: feedback_feedback.object_id
NOT NULL constraint failed: feedback_feedback.content_type_id

发生这种情况是因为反馈对象的 genericforeignkey 不为 NULL:

class Feedback(models.Model):
    comment = models.TextField(verbose_name='Comment', max_length=300, blank=True, null=True)
    client = models.ForeignKey(Client, verbose_name="Client feedback", related_name="feedbacks")

    limit = models.Q(app_label='core', model='store') | models.Q(app_label='core', model='vendor')
    content_type = models.ForeignKey(ContentType,
                                     limit_choices_to=limit)
    object_id = models.PositiveIntegerField(verbose_name="Related object ID")
    content_object = GenericForeignKey('content_type', 'object_id')

    class Meta:
        app_label = 'feedback'

我如何创建一个关于 POST 方法的反馈对象?

这是请求的示例feedback/store/(?P<store_id>\d+)/

{
  "comment": "Nice store",
  "client": 1
}
4

1 回答 1

3

将 store 设置为 serializer.object:

@api_view(['POST'])
def store_feedback_view(request, store_id):
    serializer = FeedbackSerializer(data=request.DATA)
    if serializer.is_valid():
        # this line added:
        serializer.object.content_object = get_object_or_404(Store, id=store_id)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
于 2014-10-21T13:30:16.063 回答