开发者

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'"] 


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜