【问题标题】:Create a field whose value is a calculation of other fields' values创建一个字段,其值是其他字段值的计算
【发布时间】:2012-07-12 23:56:42
【问题描述】:
class PO(models.Model)
    qty = models.IntegerField(null=True)
    cost = models.IntegerField(null=True)
    total = qty * cost

我将如何解决上面的total = qty * cost。我知道这会导致错误,但不知道如何处理。

【问题讨论】:

    标签: python django


    【解决方案1】:

    您可以将total 设为property 字段,请参阅docs

    class PO(models.Model)
        qty = models.IntegerField(null=True)
        cost = models.IntegerField(null=True)
    
        def _get_total(self):
           "Returns the total"
           return self.qty * self.cost
        total = property(_get_total)
    

    【讨论】:

    • 有什么方法可以计算数量和成本吗?
    • total 的行为就像一个字段,您可以像其他字段一样通过类对象访问它。
    • 这个问题是你不能通过查询集访问总... :(
    • 如果值是计算资源密集型的值,并且您只想在其他字段更改时执行此操作,这也无济于事。如果您不使用实际字段,则没有简单的方法将计算值存储在数据库中。
    • 该字段在PO._meta.get_fields() 中也不可见。 GenericRelation 等其他计算字段将在此处列出。从django.forms.fields.Field 继承的方法将是非常可取的!
    【解决方案2】:

    Justin Hamades answer

    class PO(models.Model)
        qty = models.IntegerField(null=True)
        cost = models.IntegerField(null=True)
    
        @property
        def total(self):
            return self.qty * self.cost
    

    【讨论】:

    • @ahsan 的回答有什么问题,正是您需要的?
    • 这是错误的,因为 total 不是属性,而是方法。
    • @MarlinForbes 不是 total = property(_get_total) identical@property?检查here
    • @agconti 是的,它的结果是完全一样的。感谢您的参考。它帮助我更多地了解了装饰器。
    • 它帮助我自信地使用装饰器,而不是调用函数作为函数的参数。我们这些 python 新手通常更喜欢使用 Ahsan 的答案。这是 Python 的一个强大功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    相关资源
    最近更新 更多