tortoise / tortoise/tortoise-orm

Custom Managers should be inherited to subclasses

Open
#1,031 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.6k
Forks
516
Avg merge
2d 21h
Merged PRs (30d)
9

Description

Is your feature request related to a problem? Please describe.
I want to be able to declare a custom Manager in my BaseModel with class Meta: abstract = True and that this Manager gets reused to all my models inheriting BaseModel.

Describe the solution you'd like
I would expect that this would suffice, but it doesn't. The User model will use the default Manager instead of the one declared in SoftDeleteModel.

class SoftDeleteManager(Manager):
    def get_queryset(self) -> QuerySet:
        return super().get_queryset().filter(deleted=False)

class SoftDeleteModel(Model):
    deleted = fields.BooleanField(default=False)
    all_objects = Manager()

    class Meta:
        abstract = True
        manager = SoftDeleteManager()

class User(SoftDeleteModel):
    name = fields.CharField(max_length=50)

Describe alternatives you've considered
As a workaround, I had to do this:

class SoftDeleteModel(Model):
    deleted = fields.BooleanField(default=False)
    all_objects = Manager()

    class Meta:
        abstract = True
        manager = SoftDeleteManager()

    def __init_subclass__(cls, **kwargs):
        cls._meta.manager = cls.Meta.manager(model=cls)
        super().__init_subclass__(**kwargs)

Also, this holds true to everything stored inside the Meta class. So probably the real solution is to load all Meta info from the parent classes in models.Model (if it's an abstract one maybe?).

def __init_subclass__(cls, **kwargs):
    if cls.Meta.abstract:
        cls._meta = cls.Meta
    super().__init_subclass__(**kwargs)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing models.Model and the Meta handling involved during subclass creation, including the init_subclass workaround shown in the issue. Reproduce the SoftDeleteModel and User example, then inspect how abstract parent metadata and managers are currently handled. Done means inherited abstract-model manager behavior works for User without the workaround, with coverage for the reported example.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
databases
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.