起初并不直观,但是答案就摆在我们面前。
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 querymatches = 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.
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)