如何做多对多Django查询以找到2位作者的书? [英] How to do many-to-many Django query to find book with 2 given authors?
本文介绍了如何做多对多Django查询以找到2位作者的书?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个查询,需要准确筛选2位作者的ID
I have a query that requires to filter exactly 2 authors with the ID
理论上,
Book.objects.filter(author__id=1, author__id=2).
这是不可能的。
我可以解决这个问题吗?
How can I solve this problem?
干杯,
米奇
推荐答案
首先,但答案是在我们面前。
Not intuitive at first but the answer is right in front of us.
Book.objects.filter(author__id=1).filter(author__id=2)
如果要完全匹配,您可以进一步过滤这些结果,有两个作者。
If you want an exact match, you could potentially further filter this result by those items that only have exactly 2 authors.
Book.objects.annotate(count=Count('author')).filter(author__id=1)\
.filter(author__id=13).filter(count=2)
如果你想要完全匹配动态的,这样的东西怎么样?:
If you want exact matches dynamically, how about something like this?:
def get_exact_match(model_class, m2m_field, ids):
query = model_class.objects.annotate(count=Count(m2m_field))\
.filter(count=len(ids))
for _id in ids:
query = query.filter(**{m2m_field: _id})
return query
matches = get_exact_match(MyModel, 'my_m2m_field', [1, 2, 3, 4])
# matches is still an unevaluated queryset, so you could run more filters
# without hitting the database.
这篇关于如何做多对多Django查询以找到2位作者的书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文