gpt4 book ai didi

django - Django:对列表中的所有项目进行匹配的ManyToMany过滤器

转载 作者:行者123 更新时间:2023-12-03 13:31:30 26 4
gpt4 key购买 nike

我有这样的Book模型:

class Book(models.Model):
authors = models.ManyToManyField(Author, ...)
...

简而言之:

我想检索作者严格等于给定作者集的书籍。我不确定是否有单个查询可以执行此操作,但是任何建议都会有所帮助。

总而言之:

这是我尝试过的((无法运行并得到AttributeError)
# A sample set of authors
target_authors = set((author_1, author_2))

# To reduce the search space,
# first retrieve those books with just 2 authors.
candidate_books = Book.objects.annotate(c=Count('authors')).filter(c=len(target_authors))

final_books = QuerySet()
for author in target_authors:
temp_books = candidate_books.filter(authors__in=[author])
final_books = final_books and temp_books

...这就是我得到的:
AttributeError: 'NoneType' object has no attribute '_meta'

通常,如何像我的情况那样,以其ManyToMany字段包含一组给定对象为约束来查询模型?

ps:我发现了一些相关的SO问题,但找不到清晰的答案。任何好的指针也将有所帮助。谢谢。

最佳答案

与@goliney的方法类似,我找到了一个解决方案。但是,我认为效率可以提高。

# A sample set of authors
target_authors = set((author_1, author_2))

# To reduce the search space, first retrieve those books with just 2 authors.
candidate_books = Book.objects.annotate(c=Count('authors')).filter(c=len(target_authors))

# In each iteration, we filter out those books which don't contain one of the
# required authors - the instance on the iteration.
for author in target_authors:
candidate_books = candidate_books.filter(authors=author)

final_books = candidate_books

关于django - Django:对列表中的所有项目进行匹配的ManyToMany过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13270513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com