D. Joe
D. Joe

Reputation: 57

How to do calculated fields in peewee?

How might one make a calculated field in a model definition? Is it possible to perform the calculation inside the generated sql query? The following fruit_difference would be the member in the peewee model I want to achieve.

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

Upvotes: 3

Views: 1556

Answers (1)

giliev
giliev

Reputation: 3058

I think what you need is a property. If you use the Python built in property, it will be evaluated in Python. If you want to do it on Database level, I guess you should use Hybrid Property.

This is a good example from the documentation:

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.

Upvotes: 3

Related Questions