【发布时间】: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