【问题标题】:Filter Generic Foreign Key过滤通用外键
【发布时间】:2015-02-04 22:22:34
【问题描述】:

是否有更“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)

models.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)

【问题讨论】:

  • 快速修复:使用列表理解 [cit for cit in sw.full_citations.all() if cit.is_primary]
  • 谢谢你,@Alvaro!这绝对有帮助。只是想知道是否有一种方法可以过滤 FullCitation 对象本身,它会更像 Django ......如果没有,我肯定会使用列表推导!
  • 您也可以使用生成器理解,(x for x in y) 来延迟数据库查询,仅在必要时执行。

标签: python django generic-foreign-key


【解决方案1】:

理解应该是过滤查询集的最后手段。最好让它们尽可能长时间地保留为 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)

【讨论】:

  • 这几乎就在那里,但并不完全(绝对符合我正在寻找的内容!)- 我需要一个“级别”的过滤。我不仅要过滤 SupportedProgram 模型,还要过滤 Supported Program 的特定实例。所以,我想要 SupportedProgram 为“Program1”的所有 FullCitations,然后,在这些 FullCitations 中,我只想要那些 is_primary=True....
  • @steph 更新为过滤特定 SupportedProgram 实例。
猜你喜欢
  • 2014-08-13
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 2021-07-27
  • 2021-07-02
  • 2019-06-18
  • 2013-06-01
  • 2012-03-07
相关资源
最近更新 更多