您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

如何进行多对多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 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.
Go 2022/1/1 18:41:39 有317人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶