开发者

Is there a cleaner way to chain filters with the Django ORM?

I've been doing this:

Model.objects.filter(key1=value1)\
             .exclude(key2=value2)\
             .order_by('key3')\
  开发者_Python百科           .select_related(depth=1)

but am hating the \. Is there a cleaner style?


Or, you can take advantage of the fact that Django QuerySet operations are cumulative, and lazy:

 myobjects = Model.objects.filter(key1=value1)
 myobjects = myobjects.exclude(key2=value2)
 myobjects = myobjects.order_by('key3')
 myobjects = myobjects.select_related(depth=1)


Parens will prevent Python from breaking it up until closed.

(
  Model.objects.filter(key1=value1)
               .exclude(key2=value2)
               .order_by('key3')
               .select_related(depth=1)
)


Like Ignacio said, but you can also close the parens on the next line instead of wrapping the whole thing.

Model.objects.filter(key1=value1
              ).exclude(key2=value2
              ).order_by('key3'
              ).select_related(depth=1)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜