【发布时间】:2017-12-28 12:28:03
【问题描述】:
我正在阅读 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() 和from_db_value() 是Field 类上的两个方法,它们涉及从数据库加载值并反序列化它们。另外,在Field class 的to_python() 方法的文档字符串中,它说它应该被子类覆盖。所以,我查看了JSONField。你猜怎么着,它不会覆盖它。此外,from_db_value() 甚至没有在Field 上定义(也没有在JOSNField 上定义)。
那么这里发生了什么?这让我们很难理解 JSONField 如何获取值并将它们转换为 json 并将它们存储在数据库中,而当我们查询数据库时则相反。
我的问题总结:
- 为什么
to_python()没有在JSONField中被覆盖? - 为什么
from_db_value()没有在JSONField中被覆盖? - 为什么
from_db_value()甚至没有在Field上定义? -
JSONField如何以 pythondict为例,将其转换为 JSON 字符串,并将其存储在数据库中? - 它是如何反其道而行之的?
很抱歉有很多问题,但我真的很想了解这一点,而且文档有点缺乏 IMO。
【问题讨论】: