具有数百个字段的Django模型 [英] Django model with hundreds of fields
问题描述
我有一个具有数百个属性的模型.这些属性可以具有不同的类型(整数,字符串,上载的文件等).我想从最重要的属性开始逐步实现这个复杂的模型.我可以想到两种选择:
I have a model with hundreds of properties. The properties can be of different types (integer, strings, uploaded files, ...). I would like to implement this complex model step by step, starting with the most important properties. I can think of two options:
- 将属性定义为常规模型字段
- 定义一个单独的模型以分别保存每个属性,并使用
ForeignKey
将其链接到主模型
- Define the properties as regular model fields
- Define a separate model to hold each property separately, and link it to the main model with a
ForeignKey
我还没有找到关于如何使用django处理具有很多属性的模型的任何建议.两种方法的优点/缺点是什么?
I have not found any suggestions on how to handle models with lots of properties with django. What are the advantages / drawbacks of both approaches?
推荐答案
您绝对应该不将您的属性定义为ForeignKeys.每当您需要一个完整的模型时,您的数据库服务器就必须制作数百个 JOIN
,从而破坏您的性能.
You definitely should not define your properties as ForeignKeys. Every time you need a full model, your database server will have to make hundreds of JOINs
, therefore ruining your performance.
如果几乎每次访问模型都需要属性,则应将它们保留在同一模型中.如果没有,您可以创建一个单独的 Properties
模型,然后通过 OneToOneField
将其链接到原始模型.
If your properties are needed almost every time you access the model, you should keep them in the same model. If not, you could make a separate Properties
model and link it to your original model via OneToOneField
.
我个人有这样的经历.我们必须构建一个酒店推荐引擎,那时我们使用的是 Drupal .随着Drupal将每个自定义属性存储在单独的MySQL表中,我们很快意识到我们应该切换框架,因为每个查询都使我们的生产服务器崩溃(20个以上的JOIN对MySQL来说是致命的事情).顺便说一句,我们最终使用了基于 ElasticSearch 的自定义解决方案,该解决方案可以很好地处理数百个字段.
I personally had such an experience. We had to build a hotel recomendation engine, and we were using Drupal back then. And as Drupal stores every custom property in a separate MySQL table, we quickly realised we should switch the framework, because every single query crashed our production servers (20+ JOINs are a deadly thing to MySQL). BTW, we ended up using a custom solution based on ElasticSearch, which handles hundreds of fields just fine.
更新:如果您幸运地使用了最新版本的PostgreSQL,则可以使用
Update: If you're lucky enough to be using a recent version of PostgreSQL, you could leverage the JSONField
storage to pack all your fields to a single model field. Note, though, that you'll have to implement a validation scheme by yourself.
这篇关于具有数百个字段的Django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!