从同一模型中的其他类获取模型属性

时间:2018-11-30 11:27:41

标签: python django python-3.x django-models

如何在同一模型中获得另一个类的价值?
我也可以使用属性吗? 我想在Stats类中使用Finance.net_income和Finance.net_margin。我尝试搜索anwser,但找不到它,我对django还是陌生的。

class Stats(models.Model):
    stock = models.ForeignKey(Stock, on_delete=models.CASCADE)
    shares_outstanding = models.FloatField(default=0)  

    @property
    def earnings_per_share(self):
        ####### ISSUE IS HERE #####
        return Finance.net_income / self.shares_outstanding

class Finance(models.Model):
    stock = models.ForeignKey(Stock, on_delete=models.CASCADE)
    total_revenue = models.FloatField(default=0) 
    operating_income = models.FloatField(default=0) 
    date = models.DateField(null=True, blank=True)
    net_income = models.FloatField(default=0) 
    cash = models.FloatField(default=0) 
    total_debt = models.FloatField(default=0) 

    @property
    def operating_margin(self):
        if self.total_revenue:
            now = (self.operating_income / self.total_revenue)*100
        else:
            now = 0
        return now

    @property
    def net_margin(self):
        if self.total_revenue:
            now = (self.net_income / self.total_revenue)*100
        else:
            now = 0
        return now

2 个答案:

答案 0 :(得分:4)

尝试这样:

@property
def earnings_per_share(self):
   total_earnings_per_share = 0 
   for finance in self.stock.finance_set.all():
         total_earnings_per_share += finance.net_income / self.shares_outstanding
   return total_earnings_per_share

好吧,您不会得到一个Finance实例,因为它是Finance与Stock之间的外键,这意味着一只股票可以具有多个Finance。

答案 1 :(得分:1)

鉴于您要计算Finance与对象Stock的{​​{1}}相同的Stock sum ,您可以使用以下方法进行计算:

Stat

或更具有描述性的过滤器:

from django.db.models import Sum

@property
def earnings_per_share(self):
    return Finance.objects.filter(
        stock_id=self.stock_id
    ).aggregate(
        total=Sum('net_income')
    )['total'] / self.shares_outstanding

如果没有所有from django.db.models import Sum @property def earnings_per_share(self): return Finance.objects.filter( stock__stats=self ).aggregate( total=Sum('net_income') )['total'] / self.shares_outstanding对象都具有一个或多个Stats对象,则Finance将返回SumNone),在这种情况下,我们可能想要返回NULL。我们可以为此使用Coalesce [Django-doc]函数:

0