tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

Does Tortoise supports hybrid methods/properties?

Open guiscaranse opened this issue 4 years ago • 2 comments

I was wondering if Tortoise has support for Hybrid Methods/Properties such as SQLAlchemy and Pony does but couldn't find anything mentioned on the documentation and even roadmaps.

guiscaranse avatar Jan 21 '21 20:01 guiscaranse

I was wondering if Tortoise has support for Hybrid Methods/Properties such as SQLAlchemy and Pony does but couldn't find anything mentioned on the documentation and even roadmaps.

It works the exact same way in tortoise - i just don't think it's documented.

For example:

class Thing(models.Model):
    field_1 = fields.IntField(...)
    field_2 = fields.IntField(...)

    def add_things(self):
        return self.field_1 + self.field_2

    def more_than_number(self, number):
        return self.add_things() > number

await Thing.create(
    id=1,
    field_1=2,
    field_2=3
)
thing = await Thing.get(id=1)
added_things = thing.add_things()
more_than = thing.more_than_number(6)
print(added_things) ## 5
print(more_than) ## False

dstlny avatar Jan 21 '21 23:01 dstlny

Hybrid properties allow you to use them in queries, you've just created helper methods inside your model. I think @guiscaranse as well as I want to be able to do something like:

class Thing(models.Model):
    field_1 = fields.IntField(...)
    field_2 = fields.IntField(...)

    @hybrid_property
    def field_3_not_in_db(self):
        return self.field_1 < self.field_2

await Thing.create(
    id=1,
    field_1=2,
    field_2=3
)

# All Things where field_1 < field_2
thing = await Thing.get(field_3_not_in_db=True)

Where you can query using the hybrid/virtual property in orm queries and the sql gets translated.

@dstlny

alexf-bond avatar May 06 '22 15:05 alexf-bond