1

Is there a more "Python/Django" way to query/filter objects by generic foreign key? I'm trying to get all FullCitation objects for a particular software, where is_primary is True.

I know I can't do this but I want to do something like this:

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 # My current attempt

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

1 回答 1

4

理解应该是过滤查询集的最后手段。最好让它们尽可能长时间地保留为 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)
于 2015-02-05T00:38:50.993 回答