Django多对多交叉过滤

Mou*_*bar 7 python django orm django-queryset

为了简单起见,我们说我只有2个模型:Book,Author

class Author(models.Model):
    name = models.CharField(max_length='100')
    ...

class Book(models.Model):
    name = models.CharField(max_length='100')
    authors = models.ManyToManyField(Author)
    ...
Run Code Online (Sandbox Code Playgroud)

我想使用作者列表过滤书籍.我试图做的是:

authors = [...] # a list of author objects
Books.objects.filter(authors__in=authors)
Run Code Online (Sandbox Code Playgroud)

但是在这里,当我想要ANDed时,作者将被ORed.有没有办法和多对多过滤?

dok*_*ebi 9

你可以和一起Q对象一起:

q = Q()
for author in authors:
    q &= Q(authors=author)
Books.objects.filter(q)
Run Code Online (Sandbox Code Playgroud)

要排除列表外具有作者的书籍,您可以将查询限制为具有列表中作者数量的书籍:

Books.objects.annotate(count=Count('authors')).filter(count=len(authors)).filter(q)
Run Code Online (Sandbox Code Playgroud)

更新:

根据评论,我认为要求是让列表中至少有一位作者撰写的所有书籍,但排除列表外任何作者的书籍.

因此,我们构建一个查询集,选择我们讨厌的作者:

# this queryset will be embedded as a subquery in the next
bad_authors = Author.objects.exclude(name__in=['A1', 'A2'])
Run Code Online (Sandbox Code Playgroud)

然后排除它们以找到我们想要的书籍:

# get all books without any of the bad_authors
Books.objects.exclude(authors__in=bad_authors)
Run Code Online (Sandbox Code Playgroud)

这将返回除列表之外的人创作的所有书籍.如果您还想排除那些没有列出作者的内容,请添加另一个排除调用:

Books.objects.exclude(authors__in=bad_authors).exclude(authors=None)
Run Code Online (Sandbox Code Playgroud)

这将只留下一个或多个好书的书籍!