Django ManytoMany 检索同时满足条件的所有对象

Django ManytoMany retireving all objects that fulfill a condition simoultaneously

在查询中使用 Django 模型示例 (https://docs.djangoproject.com/en/1.8/topics/db/queries/):

如何使用过滤功能 select 所有作者姓名以 R 开头的条目?

您使用双下划线语法,如 further down that page 所述。

Entry.objects.filter(authors__name__startswith='R')

编辑

所以你真正想做的是排除所有那些不是以R开头的作者。你可以用Q对象和[​​=12=]来做到这一点运算符:

from django.db.models import Q
Entry.objects.exclude(~Q(authors__name__startswith='R'))

对于这样的任务,我能想到一个棘手的解决方案。 (未测试)

Entry.objects \
    .annotate(num_authors=Count('authors')) \
    .filter(authors__name__startswith='R')
    .annotate(num_authors_with_r=Count('authors')) \
    .filter(num_authors=F('num_authors_with_r'))

有什么想法?

  1. 我们得到所有作者的数量。
  2. 进行过滤
  3. Return 只有过滤作者的行计数 == 所有作者计数