일반 외래 키로 개체를 쿼리/필터링하는 데 더 많은 "파이썬/장고"방법이 있습니까? 저는 특정 소프트웨어에 대한 모든 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)
Quickfix : 목록 comprehesion를 사용 [ cit. cit (주)의 경우 cit.is_primary] – Alvaro
감사합니다. @Alvaro! 확실히 도움이됩니다. 그냥 FullCitation 객체 자체를 필터링하는 방법이 있는지 궁금해지면 Django-ish가 될 것입니다 ... 그렇지 않다면 확실히 목록 이해력을 사용할 것입니다! – steph
또한 생성자 이해력'(x for x in y)'를 사용하여 데이터베이스 쿼리를 지연시키고 필요할 때만 수행 할 수 있습니다. –