如何进行多对多Django查询以找到2位给定作者的书?

如何进行多对多Django查询以找到2位给定作者的书?,第1张

如何进行多对多Django查询以找到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 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.


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5646762.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存