tortoise / tortoise-orm

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

I need OuterRef #1000

Open oyish opened 2 years ago

oyish commented 2 years ago

Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

i need outerref to create prefetch & limit

Describe the solution you'd like A clear and concise description of what you want to happen.

post_prefetch = Prefetch("posts",Post.filter(user_id=OuterRef("id")).limit(5)))
user_posts = await User.all().prefetch_related(post_prefetch)

result:

>>> user_posts[0].posts
[post 1, post 2, post 3, post 4, post 5]

Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

Additional context Add any other context about the feature request here.

VladimirAganeev commented 2 years ago
post_prefetch = Prefetch(relation='posts', queryset=Post.all().limit(5))
user_posts = await User.all().prefetch_related(post_prefetch)

It's not necessary to use OuterRef

But OuterRef need to case like this

    customers = await Customer.all().annotate(
        earliest_delivery_time=Subquery(
            Order.filter(customer_id=OuterRef('id')).limit(1).values_list('delivery_time')
        )
    ).group_by('earliest_delivery_time')

I can't annotate field from related model by using prefetch

TrixiS commented 1 year ago

post_prefetch = Prefetch(relation='posts', queryset=Post.all().limit(5)) user_posts = await User.all().prefetch_related(post_prefetch)

This thing does not work by the way. .limit(5) limits prefetch query globally, so you would have only 5 posts for all of your users.

Bumping this issue cause I need to fetch a limited set of related records too, but haven't found a way for this

xalien10 commented 1 month ago

Is OuterRef already available in tortoise-orm or not? We need it to write better Subquery using tortoise-orm ?