2017-02-19 45 views
1

我有一個父和子類存放在父模型兒童模型的計數

class parent(models.model): 
    countChidlren = #count of the total children of this parent 

class childeren(models.model): 
    parent = models.ForeignKey(parent) 

我想在父childeren的計數,但沒有對如何去做任何想法。?

回答

0

簡單的方式來做到這一點...

class Parent(models.model): 

    def total_childrens(self): 
     return Children.objects.filter(parent__pk=self.pk).count() 

class Children(models.model): 
    parent = models.ForeignKey(Parent) 

的測試,

>>> Parent.objects.first().total_childrens() 
29 
>>> 

你也可以使用@property

class Parent(models.model): 

    @property 
    def total_childrens(self): 
     return Children.objects.filter(parent__pk=self.pk).count() 

進行測試;

>>> Parent.objects.first().total_childrens 
29 
>>> 
相關問題