Selecting related foreignkeys in Django
Say I have two models, Article and Category:
class Article(models.Model):
category = models.ForeignKey(Category, related_name='articles')
class Category(models.Model):
...
When I run Category.objects.select_related()
, the ORM does not select the articles. I realize it's because of the way the foreignkey is shuffled around, but I'm not sure how to go 开发者_开发百科about doing that. Any ideas?
Here's what I ended up doing, at the advice of the kind people on #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)
精彩评论