开发者

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜