加快Django&具有简单JSON字段的Postgres [英] Speed up Django & Postgres with simple JSON field
问题描述
我有一个非常复杂的模型,其中包含FK和M2M的许多相关模型,它们之间也有很多关系,等等。
I have a very very complex model with lots of related models by FK and M2M which are also have lots of relations, etc.
因此,呈现了一个这样的对象是一个非常昂贵的SQL操作,我想对其进行优化。 (select_related和prefetch_related帮助,但有一点帮助)
So, rendering a list of such objects is a very expensive SQL operation, and i want to optimise it. (select_related and prefetch_related help, but a little)
我可能有一个非常愚蠢但很简单的想法-定义保存方法,该方法会将所有对象的数据序列化到字段存储中JSON
I have maybe a very stupid but very simple idea - define save method, that will serialize all object's data to a field stores JSON
要做类似的事情:
class VeryComplexModel(models.Model):
# some_field
# some_field
# ...
json = models.TextField()
def save(self):
json = serialize(self)
在views.py中:
in views.py:
complexModels = ComplexModel.objects.get_values(json)
并在模板中:
{% for m in complexModels %}
{{ m.some_field }}
{{ m.some_field.some_fields.some_field }}
{% endif %}
这是个坏主意吗?总的来说,也许这是个好主意,但我应该使用更合适的东西,例如特殊的JSON字段之类的东西?
Is it a bad idea? Maybe it is a good idea in general, but I should use more suitable stuff like special JSON field or something?
Big thanx寻求建议!
Big thanx for advices!
推荐答案
Django支持PostgreSQL的JSONField,下面是示例
Django supports JSONField for PostgreSQL, here is the example
from django.contrib.postgres.fields import JSONField
from django.db import models
class Dog(models.Model):
name = models.CharField(max_length=200)
data = JSONField()
def __str__(self): # __unicode__ on Python 2
return self.name
您也可以在此链接 https://docs.djangoproject.com/en/dev/ref/contrib/postgres/fields/#jsonfield
还可以在postgresql中试用HStoreField,HStoreField比JSONField更快,要使用HSTORE,您需要启用Hstore扩展在Postgresql中
also you can try out HStoreField in postgresql, HStoreField is faster than the JSONField, for using HSTORE you need to enable Hstore extension in Postgresql
postgres_prompt=> create extension hstore;
在您的迁移文件中,您需要添加此文件
in your migration file you need to add this
from django.contrib.postgres.operations import HStoreExtension
class Migration(migrations.Migration):
...
operations = [
HStoreExtension(),
...
]
这是在模型中使用Hstore的示例:
here is an example of using Hstore in your models:
from django.contrib.postgres.fields import HStoreField
from django.db import models
class Dog(models.Model):
name = models.CharField(max_length=200)
data = HStoreField()
def __str__(self): # __unicode__ on Python 2
return self.name
要了解更多信息,请转到l: https://docs.djangoproject.com/zh-CN/1.9/ref/contrib/postgres/fields/#hstorefield
to know more about this go to the l: https://docs.djangoproject.com/en/1.9/ref/contrib/postgres/fields/#hstorefield
这篇关于加快Django&具有简单JSON字段的Postgres的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!