tortoise / tortoise/tortoise-orm

CustomManager does not work with relations

Open
#918 2 comments 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

I have User model with some CustomManager with some CustomQuerySet

class User(Model):
    objects = CustomManager(qs_cls=CustomQuerySet)
    ...

And Article with User as an author

class Article(Model):
    author = fields.ForeignKeyField('app.User')
    ...

And if user obtained like:

user = (await Session.objects.first()).user

print(type(user))  # <class 'tortoise.queryset.QuerySet'> but not CustomQuerySet

So, method defined in CustomQuerySet can not longer be used

Problem location:

There is a model tortoise.models.Model with method:

@classmethod
def filter(cls: Type[MODEL], *args: Q, **kwargs: Any) -> QuerySet[MODEL]:
    return cls._meta.manager.get_queryset().filter(*args, **kwargs)

And it uses queryset from cls._meta.manager
However cls._meta.manager is always tortoise.manager.Manager ignoring any objects = CustomManager(...) defined in final model, because of tortoise/models.py:MetaInfo:168:

class MetaInfo:
    __slots__ = (
        ...
    )

    def __init__(self, meta: "Model.Meta") -> None:
        self.abstract: bool = getattr(meta, "abstract", False)
        self.manager: Manager = getattr(meta, "manager", Manager())

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 in tortoise/models.py at MetaInfo.init and trace how Model.filter uses cls._meta.manager.get_queryset(). Compare that manager with the CustomManager declared on the concrete model, then check the relation-loading path using the example models. Done means related User instances preserve the custom queryset type and its methods.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.