How to order by prefetched set values?

71 views
Skip to first unread message

Vlasov Vitaly

unread,
Aug 28, 2019, 8:47:27 AM8/28/19
to Django users
For example, i have 2 models Person and Numbers( number and ForeignKey(Person)

In queryset i get all persons with their related numbers. And i use `queryset` parameter to `Prefetch` object to filter these numbers. Result numbers_set can contain only 1 or 0 Number object. Number's table can contain any numbers for concrete Person, that's why i need prefetch filter.

Here is my code:

persons = Person.objects.all().prefecth_related(Prefecth('numbers_set', queryset=<numbers_filter>))

My problem in ordering. I need to order `persons` by numbers_set__number. But ordering working by all numbers for concrete person instead of prefetched set.

I can't use any annotation function to get this number since numbers are random and any does not match. Only filter can be used.

So how i can order_by prefetched numbers_set with only 1 or 0 value?

Thank you.

P.S. I read this SO question: https://stackoverflow.com/questions/52518569/django-2-0-order-a-queryset-by-a-field-on-the-prefetch-related-attribute
answer does not work.
I use to_attr='numbers' in Prefetch object and got exception: Cannot resolve keyword 'numbers' into field
Reply all
Reply to author
Forward
0 new messages