Ben
Ben

Reputation: 16710

Conditional order_by statements, Django

I want to incorporate a sorting feature which allows for multiple sorting variables.

I tried to pass .order_by() a function but it keeps failing when I try to include multiple fields. How do I do this?

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 the traceback:

   Invalid order_by arguments: ["'bedrooms','bathrooms'"] 

Upvotes: 6

Views: 6955

Answers (1)

user166390
user166390

Reputation:

See Django Book: Chapter 5 Models:

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

That is, the correct invocation is:

order_by('bedrooms', 'bathrooms')

In context, consistent with the original question:

def sorts():
    sort = ['bedrooms', 'bathrooms']
    return sort

posts = Post.objects.filter(**keyword_args).order_by(*sorts())

Happy coding.

Upvotes: 24

Related Questions