2013-03-22 75 views
0

我需要得到所有接觸屬於一個的總數,但是從模型中調用一批 ....Django的獲得上一個ForeignKey數

這將有助於解釋

模型(全未顯示)

class Batch(models.Model): 
    #FK 
    group = models.ForeignKey(Group, null=True, blank=True) 


class Group(models.Model): 
    name = models.CharField(max_length=60) 



class Contact(models.Model): 

    first_name = models.CharField(max_length=60) 
    group = models.ForeignKey(Group) 

所以批次內我はNT才能做這樣的事情....

def get_contact_count(self): 
     return len(self.group.contacts) 

但由於集團擁有的關係,周圍的其他方法我掙扎。

任何選項?

回答

5
return self.group.contact_set.count() 
+0

+1要發佈同樣的,你也可以設置在一個FOREIGNKEY屬性related_name在你接觸模型,而不是使用「contact_set」。 – 2013-03-22 16:09:09

0
def get_contact_count(self): 
    return Contact.objects.filter(group=self.group).count()