2017-02-19 3 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 
>>> 
関連する問題