tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.66k stars 387 forks source link

How do I add functionality to all of my models without repeating myself? #85

Closed monospacedmagic closed 5 years ago

monospacedmagic commented 5 years ago

I want to add a _d attribute and a few classmethods and some regular methods to models by creating a subclass of tortoise.models.Model that users of my framework can use. However, subclassing Model would create a new database model, which is not what I want. From what I've seen, the Model class contains a lot of logic, and it seems not feasible to create a new class with metaclass=ModelMeta. What are my options here? Am I missing something?

abondar commented 5 years ago

Hi

There is abstract=True option for models meta, it's mentioned there https://tortoise-orm.readthedocs.io/en/latest/models.html

Is it what are you looking for?

monospacedmagic commented 5 years ago

Ohhh! Thanks, I somehow completely skipped that. It's exactly what I was looking for. :)

tcmal commented 5 years ago

When using abstract=True, it seems like the child classes don't inherit fields, ie:

class Entity(Model):
    x = fields.IntField()
    y = fields.IntField()
    class Meta:
        abstract = True

class ChestEntity(Entity, Model):
    level = fields.IntField()
    opened = fields.BooleanField()

Doesn't create an entity table but just leaves the chestentity table as id, level & opened.

Am I misunderstanding this feature?

grigi commented 5 years ago

Try just inheriting from Entity instead of both Enitity and Model?

grigi commented 5 years ago

I realised we don't have a detailed example in the docs for this, nor is it part of the test suite... :disappointed:

tcmal commented 5 years ago

Still doesn't seem to work.

grigi commented 5 years ago

@tcmal Can you please check with release v0.12.4 ? new docs: https://tortoise-orm.readthedocs.io/en/latest/models.html#inheritence