【问题标题】:Django filter on generic relationship (unique constraint exception)Django过滤通用关系(唯一约束异常)
【发布时间】:2019-10-10 12:52:31
【问题描述】:

我有一个模型,它指向一个通用关系。这可以是Post 对象或Reply 对象。

class ReportedContent(models.Model):

    reporter = models.ForeignKey(User, on_delete=models.CASCADE)

    # Generic relation for posts and replies
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()

    class Meta:
        unique_together = ('reporter', 'object_id', 'content_type')

我想在收到duplicate key value violates unique constraint 异常之前检查 content_object 是否已经存在。

Django 文档提到:

# This will fail
>>> ReportedContent.objects.filter(content_object=content)
# This will also fail
>>> ReportedContent.objects.get(content_object=content)

那么如何过滤泛型关系?或者我该如何具体处理这个异常?

【问题讨论】:

  • 这看起来会很头疼。为什么不设置两个外键字段,一个用于Post,一个用于Reply,并验证这两个字段中的一个是否有值?
  • @user2896976 容易多了,谢谢你

标签: django django-generic-relations


【解决方案1】:

您可以按object_idcontent_type 进行过滤。 只要确保你做对了, 通过这种方式获取content_type

from django.contrib.contenttypes.models import ContentType
# ...

content_type = ContentType.objects.get(app_label='name_of_your_app', model='model_name')

用于处理异常:

if ReportedContent.objects.filter(object_id=content.id,content_type=content_type):
    raise Exception('your exception message')

【讨论】:

    【解决方案2】:

    我意识到这是一个老问题,但我想我会提供一种替代方法,以防其他人像我一样看到这篇文章。

    我没有在 ContentType 模型上单独使用 .get(),而是将应用程序/模型名称合并到我的过滤器中,如下所示:

    queryset = ReportedContent.objects.filter(
                   object_id=parent_object.id,
                   content_type__app_label=app_label,
                   content_type__model=model_name
               )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多