2011-10-26 104 views
-1

我有機型是這樣的:Django的查詢相關的對象

class A(Model): 
    .... 

class B(Model): 
    a = ForeignKey(A, related_name="bbb") 

class C(Model) 
    b = ForeignKey(B, related_name="ccc") 
    file = FileField(... , null=True, blank=True) 

在模板或視圖我需要一個標誌一排,如果涉及到一些C對象有文件=無(空)。 謝謝。

+1

您可能想澄清一點。也許增加一個實際的例子? – cwallenpoole

+0

例如:A - 用戶,B - PhotoAlbum,C - 照片。我的查詢選擇具有空白相冊的用戶,或者使用物件照片,但沒有上傳文件照片。只是例子。 – Alexey

回答

2

如果我理解正確的話,試試這個:

for a in A.objects.all(): 
    for b in a.bbb.all(): 
     for c in b.ccc.filter(file__isnull=True): 
      a.has_c_with_null_file = True 
      a.save() 

OR

c_without_file = C.objects.filter(file__isnull=True) 
    for c in c_without_file: 
     c.b.a.has_c_with_null_file = True 
     c.b.a.save() 

OR

A.objects.filter(b__c__file__isnull=True).update(has_c_with_null_file=True) 

如果你省略了相關的名稱,使用b_set和c_set。

+0

非常感謝。 A.objects.filter(b__c__file__isnull = True).distinct()是我需要的 – Alexey

+0

或A.objects.filter(b__c__file__isnull = True,b__c__isnull = True).distinct()!!!!有用 – Alexey