筛选满足一组条件的多对多关系 [英] Filtering on many-to-many relations that fulfill a set of criteria
问题描述
使用以下型号:
class OrderOperation(models.Model):
ordered_articles = models.ManyToManyField(Article,
through='orders.OrderedArticle')
class OrderedArticle(models.Model):
order_operation = models.ForeignKey(OrderOperation)
article = models.ForeignKey(Article)
articles = ... # some queryset containing multiple articles
如果我要查找包含至少一篇文章的订单操作,则可以按预期工作:
If I want to find order operations containing at least one article, this works as expected:
OrderOperation.objects.filter(ordered_articles__in=articles)
但是,如果我想查找订单中所有商品的订单操作,正确的方法是什么?
However, if I want to find order operations with all the articles in the order, what is the correct way to do it?
OrderOperation.objects.filter(ordered_articles=articles)
引发ProgrammingError: more than one row returned by a subquery used as an expression
错误(我理解为什么会这样).
OrderOperation.objects.filter(ordered_articles=articles)
raises a ProgrammingError: more than one row returned by a subquery used as an expression
error (I understand why actually).
推荐答案
一个简单的解决方案:
order_operations = OrderOperation.objects.all()
for article in articles:
order_operations = order_operations.filter(ordered_articles=article)
这只是一个查询,但每篇文章都有一个内部联接.对于不止几篇文章,Willem更巧妙的解决方案应该会表现更好.
It's just one query, but with an inner join per article. For more than a few articles Willem’s more ingenious solution should perform better.
这篇关于筛选满足一组条件的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!