django的 prefetch_related 只能 all() 可以用 filter ?
直接说答案
- <= Django 1.6 只能在使用代码过滤
somethings = Foo.objects.filter(author="author").prefetch_related("bar_set")
for a in somethings:
somebars = [p for p in a.bar_set.all() if p.format == 1]
* Django 1.6 >= Prefetch()对象
```
somethings = Foo.objects.filter(author="author").prefetch_related(
Prefetch(
"bar_set",
queryset=Bar.objects.filter(format=1),
to_attr="some_bars"
)
)
for a in somethings:
somebars = a.some_bars
```
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/17061058.html