python - 过滤通用外键

标签 python django generic-foreign-key

是否有更“Python/Django”的方式来通过通用外键查询/过滤对象?我正在尝试获取特定软件的所有 FullCitation 对象,其中 is_primary 为 True。

我知道我不能这样做,但我想做这样的事情:

ct_supported = ContentType.objects.get(app_label="supportedprogram", model="software")
primary_citations = FullCitation.objects.filter(content_type__name=ct_supported, object_id__in='', is_primary=True)

模型.py

class FullCitation(models.Model)
    # the software to which this citation belongs
    # either a supported software program or a non-supported software program

    limit = models.Q(app_label = 'myprograms', model = 'supportedprogram') | models.Q(app_label = 'myprograms', model = 'nonsupportedprogram') 
    content_type = models.ForeignKey(ContentType), limit_choices_to = limit, )
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    is_primary = models.BooleanField(help_text="Is this the Primary Citation for the software program?")

class NonSupportedProgram(models.Model):
    title = models.CharField(max_length=256, blank = True)
    full_citation = generic.GenericRelation('FullCitation')

class SupportedProgram(models.Model):
    title = models.CharField(max_length=256, blank = True)
    full_citation = generic.GenericRelation('FullCitation')
    # and a bunch of other fields.....

views.py # 我目前的尝试

primary_citations = []
sw_citations = sw.full_citations.all()
    for x in sw_citations:
        if x.is_primary:
            primary_citations.append(x)

最佳答案

理解应该是过滤查询集的最后手段。最好尽可能长时间地让它们保留为 QuerySet。我想这就是您要找的:

ct_supported = ContentType.objects.get_for_model(SupportedProgram))
primary_citations = FullCitation.objects.filter(content_type=ct_supported, is_primary=True)

更新: 如果要过滤特定的 SupportedProgram 实例,请执行以下操作:

my_supported = SupportedProgram.objects.get(id=instance_id_goes_here)
ct_supported = ContentType.objects.get_for_model(SupportedProgram))
primary_citations = FullCitation.objects.filter(content_object=my_supported, content_type=ct_supported, is_primary=True)

关于python - 过滤通用外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28332663/

相关文章:

python - 使用 Django (Python) 在 DynamoDB 中自动生成 key

python - 消除自定义数据结构的重复

python - 并发和 Selenium - 多处理与多线程

django-sane-testing 不启动实时服务器

python - update_or_create 的 Django GenericRelation

python - numpy图像,裁剪一侧,用黑色填充另一侧

python - 模型中的元类是否应该从对象继承

python - 如何在Django中接收存储过程Oracle的输出参数(sys_refcursor)

python - 如何在 Django 中使用通用外键引用来引用对象

python - Django 通用外键 : accessor clash when 2 models have same related_name