【问题标题】:Django PostgresqlJSONField custom decoderDjango PostgresqlJSONField 自定义解码器
【发布时间】: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


【解决方案1】:

我自己想出的解决方案是使用普通的文本字段,并使用标准的 json 函数。因此,您确实失去了查询该字段的能力,但对于简单的用例,它可以完成这项工作。

class JSONField(models.TextField):
    description = _("JSON")
    def __init__(self,*args,encoder=None,decoder=None,**kwargs):
        super(JSONField, self).__init__(*args,**kwargs)
        self.encoder = encoder
        self.decoder = decoder

    def to_python(self, value):
        """Convert our string value to JSON after we load it from the DB"""

        if value == "":
            return None
        try:
            return json.loads(value,cls=self.decoder)
        except ValueError as e:
            __log__.error("used ' instead of \"?")
        return value

    def from_db_value(self, value, expression, connection, context):
        return self.to_python(value)

    def get_db_prep_save(self, value, connection):
        if value == "":
            return ""
        if isinstance(value, str):
            return value
        try:
            dump = json.dumps(value,cls=self.encoder)
            return dump
        except Exception as e:
            __log__.error(e)
        return ""

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 2019-10-24
    相关资源
    最近更新 更多