我有一个查询,需要使用 ID 精确过滤 2 位作者
理论上,
Book.objects.filter(author__id=1, author__id=2).
这是不可能的。
我怎么解决这个问题?
干杯,
米奇
一开始并不直观,但答案就在我们面前。
Book.objects.filter(author__id=1).filter(author__id=2)
如果您想要完全匹配,您可以通过那些只有 2 位作者的项目进一步过滤此结果。
Book.objects.annotate(count=Count('author')).filter(author__id=1)\
.filter(author__id=13).filter(count=2)
如果你想要动态精确匹配,像这样怎么样?:
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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)