简体   繁体   English

通用关系上的Django过滤器(唯一约束异常)

[英]Django filter on generic relationship (unique constraint exception)

I have a model below which points to a generic relationship.我在下面有一个模型,它指向一个通用关系。 This can either be a Post object or a Reply object.这可以是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')

I would like to check if the content_object is already exists before I get a duplicate key value violates unique constraint exception.我想在获得duplicate key value violates unique constraint异常之前检查 content_object 是否已经存在。

Django documentation mentioned that: Django 文档提到:

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

So how can I filter on generic relation?那么如何过滤通用关系呢? or how can I deal with this exception specifically?或者我该如何处理这个异常?

you can filter by object_id and content_type .您可以按object_idcontent_type进行过滤。 just make sure you do it right, get content_type this way:只要确保你做对了,就这样获取content_type

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

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

for handling the exception :用于处理异常:

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

I realize this is an old(ish) question, but I thought I'd offer an alternative method in case others run across this post as I did.我意识到这是一个古老的(ish)问题,但我想我会提供一种替代方法,以防其他人像我一样遇到这篇文章。

Instead of doing a separate .get() on the ContentType model, I just incorporate the app/model names in my filter, like this:我没有在 ContentType 模型上执行单独的.get() ,而是将应用程序/模型名称合并到我的过滤器中,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM