django - 查询速度反转 OneToOneField

标签 django postgresql django-queryset

我对将文章分配给杂志的两种建模方法存有疑问。模型的一些伪代码可能是:

class Article():
  title = ...
  text = ...
  magazine = ForeignKey(Magazine, db_index=True)


class Magazine():
   ...

class ArticleMagazineAllocation():
  article = OneToOneField(Article, db_index=True)
  magazine = ForeignKey(Magazine, db_index=True)
  allocated_on = DateTimeField()

我可以从 Article 创建指向杂志的外键。或者,我可以使用 ArticleMagazineAllocation 模型连接两者,出于多种原因我更喜欢这种方式,以存储有关“分配”的额外数据。

对于第一种情况,查询将是: magazine_articles = Article.objects.filter(杂志=我的杂志)

对于第二个,查询将是: magazine_aticles = Article.objects.filter(articlemagazineallocation__magazine = mymagazine)

有很多(数百万)篇文章和几本(数百)本杂志,使用第二种方法会不会有相当大的速度损失?

最佳答案

如果您需要为需要有关关系本身的额外数据的多对多关系建模,您应该创建一个中间模型。为了直接查询相关模型,您可以在任一模型上放置一个 ManyToMany 字段,使用选项 through。要查询相关模型,您始终可以在 Django 中使用双下划线查询语法。

https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ManyToManyField.through

至于性能,您可以使用select_relatedprefetch_related 查询跨多个表的大型数据集。

关于django - 查询速度反转 OneToOneField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34106986/

相关文章:

postgresql - 插入关系 go-pg PostgreSQL

postgresql - 如何在 SELECT 等待 INSERT 提交期间等待?

Django queryset : filter DateTimeField if datetime. now() 大于字段 - 24 小时

css - django 联合提要框架 : adding CSS to RSS

javascript - 当我的导航栏折叠时如何使按钮起作用?

python - Django - 部分验证表单

sql - 列出引用 PostgreSQL 中表的存储函数

python - 按查询集中的对象排除

Python - 链接方法 : returning `self` vs returning a new cloned object

django - PyCharm 5.1 Beta 2 中 Docker Compose 远程解释器的服务名称