tortoise / tortoise/tortoise-orm

Exposing `_get_fetch_fields`

Open
#747 1 comment 1 reaction 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 am running a project with FastAPI and Pydantic, when I find that I often want to implement custom from_queryset, from_tortoise_orm, or from_queryset_single methods. I don't want to change much of the original behavior, I just want to add some extra prefetching (which is overridden if I try to prefetch before calling those methods), or sometimes I would like to inject a constant value for all objects in a queryset.

Describe the solution you'd like
I think exposing _get_fetch_fields as a classmethod would really help ease overriding the aforementioned methods. Something as simple as:

class PydanticModel(BaseModel):
    .....

    @classmethod
    def get_default_fetch_fields(cls) -> List[str]:
        return _get_fetch_fields(cls, getattr(cls.__config__, "orig_model"))

    ....

Describe alternatives you've considered
I've tried annotating a queryset with a constant value before serializing it with from_queryset, but the annotate method only allows expressions and terms. I've considered importing _get_fetch_fields and using it, but it's a private helper and I'm worried it could cause undocumented breaking changes in the future. I've also considered looping over the queryset, adding in a constant value, and then running a from_tortoise_orm to serialize the objects, but I think that's much more inefficient than a prefetch on a queryset (compared to fetch_related on every iteration, however, I'm not entirely sure).

Additional context
This is just a suggestion, I am very open to criticism and alternatives/ideas I have not thought of.

Also, thank you for an awesome ORM! 🎉

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 locating the private _get_fetch_fields helper and the from_queryset, from_tortoise_orm, and from_queryset_single methods mentioned in the issue. Review how their default fetch fields are determined, then check whether a classmethod exposing that behavior can be added without changing existing serialization; done means custom methods can reuse it and the relevant tests pass.

Written by the indexing model from the issue text.

Assessment

Tech stack
fastapi, python
Domain
backend, database
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.