0

我有这段代码,我想优化:

articles = Articles.objects.filter(active=True).all().order_by('-added')[start_from:per_page+start_from]
tags = dict()
for article in articles:
    tags[article.id] = Tags.objects.filter(articles=article).all()

我认为该代码可以,但它们返回错误:

articles = Articles.objects.filter(active=True).all()[start_from:per_page+start_from]
articles_tags = Tags.objects.filter(articles__in=articles).all()
tags = dict()
for article in articles:
        tags[article.id] = articles_tags.filter(articles=article).all()

错误信息

(1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'")
4

1 回答 1

0

由于您使用的是 Django 1.4,因此请尝试prefetch_related在 QuerySet 上使用。这通过运行单独的查询来获取 ManyToMany 字段,然后在 Python 中将两者结合在一起。这样,您将使用 2 个查询而不是 1 + n 个查询来检索所有数据:

# Fetch articles
articles = Articles.objects.filter(active=True) \
    .prefetch_related('tags')[start_from:per_page+start_from]

# Eat a donut
logging.info('omnomnomnom')

https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related

于 2012-08-21T21:25:25.740 回答