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
```
posted @ 2023-01-19 09:19  vx_guanchaoguo0  阅读(19)  评论(0编辑  收藏  举报