首页 > 解决方案 > TypeError: *: 'DeferredAttribute' 和 'DeferredAttribute' django 不支持的操作数类型

问题描述

下午好社区,

我是 Django 新手,为了练习,我正在建立一个金融网站。目标是用户将插入关于公司 x 的数据,例如 Apple,并且网站将执行一些度量计算以返回给用户。

到目前为止,我有两个模型:

class Company(models.Model):
#Company data
company_name = models.CharField(max_length=100)
outstanding_shares = models.IntegerField()
share_price = models.DecimalField(max_digits= 5, decimal_places=2)
revenue = models.IntegerField()
expenses = models.IntegerField()
total_assets = models.IntegerField()
total_liabilities = models.IntegerField()
current_assets = models.IntegerField()
current_liabilities = models.IntegerField()
operating_cashflows = models.IntegerField()
capex = models.IntegerField()

#Date of creation
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now= True)    
    
def __str__(self):
    return self.company_name

class Market_Cap(Company):          
market_cap= Company.share_price * Company.outstanding_shares

当我运行 python manage.py check 时,我收到以下错误:

Market_Cap market_cap= Company.share_price * Company.outstanding_shares TypeError: 不支持的操作数类型 *: 'DeferredAttribute' 和 'DeferredAttribute'

关于如何解决这个问题的任何提示?

提前非常感谢。

标签: pythondjangodjango-models

解决方案


您应该Company像这样在模型中创建一个方法:

@property
def market_cap(self):
    return self.share_price * self.outstanding_shares


推荐阅读