【问题标题】:Selecting related foreignkeys in Django在 Django 中选择相关的外键
【发布时间】:2011-04-19 16:21:05
【问题描述】:

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

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

class Category(models.Model):
    ...

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

【问题讨论】:

    标签: django django-models django-orm


    【解决方案1】:

    根据#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)
    

    【讨论】:

      猜你喜欢
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 2021-10-04
      • 2018-12-22
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多