我正在将应用程序从 python 2/Django 1.4 迁移到 python 3/Django 2.1.5。我对自定义 JSON 字段有一个奇怪的行为:class JSONField(models.TextField): """JSONField is a generic textfield that neatly serializes/unserializesJSON objects seamlessly. Main thingy must be a dict object.""" def __init__(self, *args, **kwargs): if 'default' not in kwargs: kwargs['default'] = '{}' super().__init__(*args, **kwargs) def to_python(self, value): """Convert our string value to JSON after we load it from the DB""" if not value: return {} elif isinstance(value, str): res = loads(value) assert isinstance(res, dict) return res else: return value def get_db_prep_save(self, value, connection): """Convert our JSON object to a string before we save""" if not value: return super(JSONField, self).get_db_prep_save("", connection=connection) else: return super(JSONField, self).get_db_prep_save(dumps(value), connection=connection)使用 Django 1.4,当我从数据库读取对象时会调用 JSONField.to_python(),但使用 Django 2.1.5 时不会调用:你知道为什么吗?
添加回答
举报
0/150
提交
取消