使用以下模型:
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
如果我要查找包含至少一篇文章的订单操作,则可以按预期工作:
OrderOperation.objects.filter(ordered_articles__in=articles)
但是,如果要查找订单中所有商品的订单操作,正确的方法是什么?
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)
ProgrammingError: more than one row returned by a subquery used as an expression
一个简单的解决方案:
order_operations = OrderOperation.objects.all() for article in articles: order_operations = order_operations.filter(ordered_articles=article)
这只是一个查询,但每篇文章都有一个内部联接。对于多篇文章,Willem更巧妙的解决方案应该会表现更好。