django无定形解锁jsonfield的力量
django-amorphous的Python项目详细描述
主要功能
Django Angular允许您存储通常需要的数据 如果对 它们的结构,在一个singlejsonfield中。
通过定义存储 字段类型和数据,以及用于实例化 字段。
例如:
代码:
# First import the class generator>>>fromamorphous.formsimportamorphous_gen# Than define the structure of the data>>>json_data={'first':['BooleanField',{'initial':True,'required':False},],'second':['CharField',{'initial':'This is a test'}]}
最后,从这里生成form类,您有两个选择: 创建该类的实例 或者创建一个表单,该表单的初始值由数据库中的数据设置:
>>>form_class=amorphous_gen(amorphous=json_data)>>>form_instance=form_class()# Using data from object in DB.# This creates a form class where the initial values are the values stored# in the DB# Note: the form is not bound>>>form_instance=amorphous_gen(obj.field)# this is usefull when dealing with post and get methods
为了存储数据,以非晶态所期望的格式使用db_非晶态 形式方法:
>>>for_db=form.db_amorphous()
设置属性后保存对象,其中非晶场是 在模型上保存非晶态数据的字段的名称:
用法
非晶态包含一个cbv,amorphousview,它取jsonfield的名称 希望将非晶态数据存储到非晶态字段中 希望设置模型属性:
>>>view=AmorphousView.as_view(template_name='amorphous_test/model_amo.html',model=TestModel,form_class=self.test_form_class,amorphous_field='metadata')
此视图负责按预期显示、验证和保存表单 某些方法可以被重写以添加或删除功能,就像在任何 CBV公司。
测试
运行测试:
# just amorphous' tests $ manage.py test amorphous # amorphous' tests and your tests $ manage.py test . amorphous
可能性
有了这个包,您可以在同一个字段中存储不同的模式。 假设您存储的一个数据结构已更改 但只有新数据使用新模式,旧数据不需要迁移。
因为表单类是动态生成的,并且假设没有限制 应用于非道德使用的jsonfield,表单可以根据 正在使用哪个版本。考虑如何存储表单结构,因为 这样,每个非晶场有多个模式的行为几乎 免费。
在现实世界中,这可以用于创建标记、类别,甚至 语言翻译系统。因为对于此应用程序,您需要添加或删除 动态地向它们发送项,并且架构绑定的实现将使它们 执行困难。然而,对于非晶场,它们变得微不足道。