tortoise / tortoise/tortoise-orm

fetch_related() should allow a manager to be passed as an arg.

Open
#2,234 0 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

Is your feature request related to a problem? Please describe.
I have a model where a FK related object does not show in queries because the related object isn't in the query results from the default model manager. It would be cleaner and faster to be able to pass in a manager or some other argument to allow fetch_related to return that object.

example:
class GroupOneManager(Manager):
def get_queryset(self):
return (
super()
.get_queryset()
.filter(group='One')
)

class User(BaseModel):
id = fields.CharField(pk=True, max_length=255)
group = fields.CharField(max_length=255)
all_objects = Manager()

class meta: 
    manager = GroupOneManager()

class Controls(BaseModel):
user = fields.ForeignKeyField(User)

user = await User.get(group='Two').first()
await Controls(user=user).save()
control = await Controls.all.first()
await control.fetch_related('user')
print(control.user) # Will be None because user is in group='Two' which isn't part of default manager

Describe the solution you'd like
await object.fetch_related('user', manager=GroupModelManager)
of
await object.fetch_related('user', exclude_default_manger=True)

Describe alternatives you've considered
The alternative is to do a separate lookup of the object which isn't as clean or pythonic.

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 at the fetch_related() entry point and trace how the related object's default manager is used. Reproduce the shown User, Controls, and GroupOneManager case, then add focused coverage for passing an alternate manager or bypassing the default manager; done means the related user is returned for the requested option.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.