2015-02-04 2 views
1

일반 외래 키로 개체를 쿼리/필터링하는 데 더 많은 "파이썬/장고"방법이 있습니까? 저는 특정 소프트웨어에 대한 모든 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) 
+0

Quickfix : 목록 comprehesion를 사용 [ cit. cit (주)의 경우 cit.is_primary] – Alvaro

+0

감사합니다. @Alvaro! 확실히 도움이됩니다. 그냥 FullCitation 객체 자체를 필터링하는 방법이 있는지 궁금해지면 Django-ish가 될 것입니다 ... 그렇지 않다면 확실히 목록 이해력을 사용할 것입니다! – steph

+0

또한 생성자 이해력'(x for x in y)'를 사용하여 데이터베이스 쿼리를 지연시키고 필요할 때만 수행 할 수 있습니다. –

답변

4

이해는 QuerySets를 필터링하기위한 최후의 수단이어야합니다. 가능한 한 QuerySets로 유지하는 것이 좋습니다. 업데이트

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) 
+0

거의 없지만 확실히 (정확히 내가 원하는 것을 정맥에 넣었습니다!) - 필터링이 한 단계 더 필요합니다. SupportedProgram 모델뿐만 아니라 Supported Program의 특정 인스턴스를 필터링하려고합니다. 그래서, 나는 FullCitations가 SupportedProgram, 특히, 'Program1'이고 FullCitations 중 is_primary = True 인 곳만 원한다. ... – steph

+0

@steph 특정 SupportedProgram 인스턴스를 필터링하도록 업데이트되었습니다. – dylrei

+0

정말 고마워요! @ 딜레이 – steph