如何在 peewee 中计算字段?

How to do calculated fields in peewee?

如何在模型定义中创建计算字段?是否可以在生成的 sql 查询中执行计算?以下 fruit_difference 将是我想要实现的 peewee 模型中的成员。

SELECT
    apple_count,
    orange_count,
    (apple_count - orange_count) fruit_difference
FROM fruit_vendors

我想你需要的是 属性。如果使用 属性 中内置的 Python,它将在 Python 中进行计算。如果您想在数据库级别进行操作,我想您应该使用 Hybrid Property.

这是文档中的一个很好的例子:

class Interval(Model):
    start = IntegerField()
    end = IntegerField()

    @hybrid_property
    def length(self):
        return self.end - self.start

    @hybrid_property
    def radius(self):
        return abs(self.length) / 2

    @radius.expression
    def radius(cls):
        return fn.ABS(cls.length) / 2

What is neat is that both the radius implementations refer to the length hybrid attribute! When accessed via an Interval instance, the radius calculation will be executed in Python. When invoked via an Interval class, we will get the appropriate SQL.