【问题标题】:Optimized way of fetching ManyToMany fields in django model in single query在单个查询中获取 django 模型中的 ManyToMany 字段的优化方法
【发布时间】:2011-06-03 20:52:48
【问题描述】:

我在 django 中有以下模型结构。

Category:
    - name
    - description

Tag:
    - name

Article:
    - guid
    - title
    - detail
    - tags (Many2Many with Tag)
    - cats (Many2Many with Category)

现在,在我的批量(最多 100,000 篇)文章更新工作中,我必须执行以下操作。

- for each article:
     - to check if this article has already appeared in another category
         - if yes, associate article with current category
         - if no, create article along current category
     - to check if any of associated tags are exists or not,
          - if not exists create tag, and associate with current article
          - if exists, just associated with current article

在执行此操作时,我已经拥有从数据库中获取的现有文章的字典。

由于 ManyToMany 字段对 django 中的 select_related() 等获取操作没有任何影响,有没有其他方法可以帮助我加载现有文章以及类别和标签?

【问题讨论】:

    标签: sql django performance django-models


    【解决方案1】:

    如果您在多对多关系中添加intermediary table,例如ArticleTag,您可以通过django 的ORM 查询此表并在其上使用select_related

    # Get all 'tag-relations' WITH associated articles AND tags
    articles_tags = ArticleTag.objects.all().select_related()
    

    然后您可以遍历结果以检查我是否与标签关联的特定文章...我想在 django 中没有其他方法可以直接查询表示关系的表而不指定through-model,否则你仍然可以使用原始 sql 查询来查询它。如果你有非常多的数据,这可能会产生大量的内存使用,但是你只会访问数据库一次!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多