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)
精彩评论