在Django中选择相关的外键

时间:2011-04-19 16:21:05

标签: django django-models django-orm

说我有两个模型,文章和类别:

class Article(models.Model):
    category = models.ForeignKey(Category, related_name='articles')

class Category(models.Model):
    ...

当我运行Category.objects.select_related()时,ORM不会选择文章。我意识到这是因为外键被改组的方式,但我不知道如何去做。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

根据#django上善良的人的建议,这就是我最终做的事情:

articles = Article.objects.select_related()
categories = {}

for article in articles:
    if not categories.get(article.category, None):
        categories[article.section] = []
    categories[article.category].append(article)
相关问题