我正在阅读JSONField上的the docs,这是一种特殊的postgresql字段类型。由于我打算创建一个自定义字段,它子类JSONField
,并添加了能够转换Lifts
类的功能:
class Lifts(object):
def __init__(self, series):
for serie in series:
if type(serie) != LiftSerie:
raise TypeError("List passed to constructor should only contain LiftSerie objects")
self.series = series
class AbstractSerie(object):
def __init__(self, activity, amount):
self.activity_name = activity.name
self.amount = amount
def pre_json(self):
"""A dict that can easily be turned into json."""
pre_json = {
self.activity_name:
self.amount
}
return pre_json
def __str__(self):
return str(self.pre_json())
class LiftSerie(AbstractSerie):
def __init__(self, lift, setlist):
""" lift should be an instance of LiftActivity.
setList is a list containing reps for each set
that has been performed.
"""
if not (isinstance(setlist, collections.Sequence) and not isinstance(setlist, str)):
raise TypeError("setlist has to behave as a list and can not be a string.")
super().__init__(lift, setlist)
我读过here,to_python()
和{to_python()
方法的docstring中,它表示应该由子类重写。所以,我查了JSONField
。你猜怎么着,它不会覆盖它。而且,from_db_value()
甚至没有在Field
上定义(也没有在JOSNField
上定义)。在
这是怎么回事?这使得我们很难理解JSONField如何获取值并将其转换为json并将其存储在数据库中,而当我们查询数据库时,情况恰恰相反。在
我的问题摘要:
to_python()
在JSONField
中被重写?在from_db_value()
在JSONField
中被重写?在from_db_value()
甚至没有在Field
上定义?在JSONField
如何以python dict
为例,将其转换为JSON字符串,并将其存储在数据库中?在很抱歉有很多问题,但我真的很想了解这一点,而且文件在我看来有点欠缺
对于Django数据库字段,同一数据有三种相关的状态/表示:form、python和database。对于示例
HandField
,表单/数据库表示是相同的字符串,python表示是Hand
对象实例。在如果在
JSONField
上有一个自定义字段,内部python可能是LiftSerie
实例,表单表示json字符串,发送到数据库的值是json字符串,从数据库接收的值是psycopg2从postgres返回的字符串转换而来的json结构。在关于你的问题:
python值不是自定义的,因此字段的python数据类型与预期输入相同。与
HandField
示例相反,在该示例中,输入可以通过字符串或Hand
实例。在后一种情况下,只返回输入的基本Field.to_python()
实现就足够了。Psycopg2已经将数据库值转换为json,参见5。对于其他类型,如int/
IntegerField
,也是如此。from_db_value
没有在基Field
类中定义,但是如果它存在,它肯定会被考虑在内。如果您看一下implementation of ^{Field
有一个这样命名的属性,from_db_value
就会被添加到其中。django.contrib.postgres.JSONField
有一个可选的编码器参数。默认情况下,它使用^{psycopg2自动从数据库类型转换为python类型。它叫做adaptation。Documentation for JSON adaptation解释了它的工作原理和可定制的方式。
请注意,在实现自定义字段时,我建议在开发过程中为其编写测试,尤其是在机制尚未完全理解的情况下。您可以在django-localflavor中获得此类测试的灵感。在
相关问题 更多 >
编程相关推荐