tortoise / tortoise-orm

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

Question about signals in model inheritance #1532

Open nekorrrr opened 6 months ago

nekorrrr commented 6 months ago

Is your feature request related to a problem? Please describe. I want to still be able to use signals from the parent class when inheriting I have the following code

from tortoise import fields
from tortoise.models import Model
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.signals import post_delete, post_save, pre_delete, pre_save

class BaseModel(Model):
    id = fields.IntField(pk=True)
    created_at = fields.DatetimeField(auto_now_add=True)
    create_by = fields.TextField(max_length=200,null=True)
    update_at = fields.DatetimeField(auto_now=True)
    update_by = fields.TextField(max_length=200,null=True)

    class Meta:
        abstract = True

@pre_save(BaseModel)
async def base_model_pre_save(
    sender: "Type[BaseModel]", instance: BaseModel, using_db, update_fields
) -> None:
    print("BaseModel some logic")

class Users(BaseModel):
    user_id = fields.CharField(max_length=20)
    auth_type = fields.IntField(default=1)
    first_name = fields.CharField(max_length=50, null=True)
    last_name = fields.CharField(max_length=50, null=True)
    password = fields.CharField(max_length=50)
    mail = fields.CharField(max_length=50,null=True)

    class Meta:
        unique_together=(("id", "user_id", "auth_type"))

User_R = pydantic_model_creator(Users, name="User_R")
User_I = pydantic_model_creator(Users, name="User_I", exclude_readonly=True)

@pre_save(Users)
async def users_model_pre_save(
    sender: "Type[Users]", instance: Users, using_db, update_fields
) -> None:
    print("UsersModel some logic")

Describe the solution you'd like I want to be able to print the following when I run Users.create BaseModel some logic UsersModel some logic But now it only prints one line of results UsersModel some logic

Can you help me with this problem? Or have some alternatives, then I would be very grateful!