Conditional instructions order_by, Django

I want to enable a sort function that allows you to use multiple sort variables.

I tried passing the .order_by () function, but it continues to fail when I try to include multiple fields. How to do it?

if request.GET.get('size_sort')=='1': def sorts(): sort='\'bedrooms\',\'bathrooms\'' return sort posts=Post.objects.filter(**keyword_args).order_by(sorts()) 

This returns a trace:

  Invalid order_by arguments: ["'bedrooms','bathrooms'"] 
+4
source share
1 answer

See Django Book: Chapter 5 Models :

To sort by multiple fields (where the second field is used to disambiguate the order in cases where the first is the same), use several arguments:

That is, the correct call:

 order_by('bedrooms', 'bathrooms') 

In the context, according to the original question:

 def sorts(): sort = ['bedrooms', 'bathrooms'] return sort posts = Post.objects.filter(**keyword_args).order_by(*sorts()) 

Happy coding.

+18
source

Source: https://habr.com/ru/post/1345137/


All Articles