【发布时间】:2019-11-29 05:57:44
【问题描述】:
提供自定义编码器很容易,因为我们可以设置编码器参数,但使用自定义解码器似乎是不可能的。我将如何为 Django PostgresqlField 使用自定义解码器?
例如, 我们有一个自定义 JSON 编码器:
class JSONObjectEncoder(json.JSONEncoder):
class JSONEncodable:
def encode(self):
raise NotImplementedError()
def default(self, o):
if isinstance(o,JSONObjectEncoder.JSONEncodable):
return o.encode()
return super().default(o)
如果我们想对一个类进行编码,它会是:
class Parameter(JSONObjectEncoder.JSONEncodable):
def encode(self):
return #something
postgresfield 看起来像这样:
params = PostgressJSONField(encoder=JSONObjectEncoder)
现在每个实现 JSONEncodable 的对象都可以解码为 json。 但是一旦我们有了来自数据库的 JSON,我想将它自动编码到参数类中。
【问题讨论】:
-
你能分享你的尝试吗,或者让我们知道你想要编码/解码什么
-
psycopg2 没有提供在查询中传递解码器的好方法。它确实为您提供了在the DB connection itself 上设置自定义加载方法的选项。虽然这可能不合适
标签: json django postgresql django-models