如何优化模型多选择?

时间:2012-08-21 18:50:46

标签: python django django-views

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

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'")

1 个答案:

答案 0 :(得分:0)

由于您使用的是Django 1.4,请尝试在QuerySet上使用prefetch_related。这通过运行单独的查询来获取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