我有一个模型,它指向一个通用关系。这可以是一个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)
那么如何过滤泛型关系呢?或者我该如何具体处理这个异常?