我正在阅读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()和{}是{}类上的两个方法,它们涉及从数据库加载值并反序列化它们。另外,在^{} class上的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字符串,并将其存储在数据库中?在
它是如何反其道而行之的呢?在
很抱歉有很多问题,但我真的很想了解这一点,而且文件在我看来有点欠缺