2017-10-17 13 views
1

에 전달 :장고 : 관련 개체의 관련 개체를 얻을 내가 세 가지 모델이 장고 응용 프로그램에서 템플릿

이, B 사이에 A와 B 사이에 일대 다 관계가 존재한다
class A(models.Model): 
    aId = models.AutoField(primary_key=True) 

class B(models.Model): 
    bId = models.AutoField(primary_key=True) 
    aId = models.ForeignKey(A) 

class C(models.Model): 
    cId = models.AutoField(primary_key=True) 
    bId = models.ForeignKey(B) 

로를 그리고 C. 그리고 View 클래스는 context_data입니다. 템플릿에서 C를 사용하여 Bs를 표시하고 필터링해야합니다. 해당 B와 관련된 A 및 모든 C와 관련된 모든 B를 내 템플릿 (컨텍스트)에 전달하려면 어떻게해야합니까? 두 배열에서 Bs와 Cs를 따로 얻으려고했지만 Bs로 C를 분류 할 수 없기 때문에 좋은 생각이 아닌 것 같습니다.

답변

1

A의 인스턴스가 a이라고 가정 해 보겠습니다. 당신이 prefetch related objects 할 수있는 여러 쿼리를 방지하기 위해

bs = a.b_set.all() 
for b in bs: 
    cs = b.c_set.all() 

.

1

이 코드는보기에 적합합니다. args/kwargs에 어떤 객체가 주어 졌는지 확실하지 않습니다. 당신이 검색어 세트를 결합해야하는 경우

from django.views.generic import TemplateView 

class YourView(TemplateView): 
    template_name = 'yourtemplate.html' 

    def get_context_data(self, **kwargs): 
     a = kwargs.get('a') 
     b = kwargs.get('b') 
     ctx = super().get_context_data(**kwargs) 

     ctx['all b related to a'] = a.b_set.all() 
     ctx['all c related to b'] = b.c_set.all() 
     return ctx 

, 당신은 UNION 연산자를 사용할 수 @s_puria이 제안 B 각각에 대한 CS의 여러 검색어 세트 말 https://docs.djangoproject.com/en/1.11/ref/models/querysets/#union