Wednesday, August 28, 2019

How to order by prefetched set values?

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/89b142ab-22cc-4b46-b44a-f47559607940%40googlegroups.com.

No comments:

Post a Comment