python - Django HStore : How to override a key-value model field's __getattr__ and __setattr__

标签 python django json postgresql hstore

通过 django-hstore module 在 Django 中使用 hstore,我已经开始尝试了。 .使用 hstore 的一大优势是它允许将键值存储在字段中,同时在 Postgresql 中提供合适的索引。 django-hstore(和一般的 hstore)的一大缺点是您只能将值存储为字符串。

为了克服这个问题,我认为覆盖模型字段 (hstore.DictionaryField) 会很好,这样输入到字段中的任何数据都会自动编码为 JSON,并且检索到的任何数据都会自动进行从 JSON 解码。我试图通过覆盖 __setattr__ 方法来做到这一点,但这会导致大量错误(当设置字段的所有属性时)。对正确的方法有什么想法吗?

到目前为止我有什么(我在专注于 setter 的同时注释掉了 getter 部分,但将其保留以显示我的想法):

import simplejson as json

from django.db import models
from django_hstore import hstore


def _unpack_json(value):
    try:
        value = json.loads(value)
    except TypeError:
        pass
    return value


class HStoreJsonDict(hstore.DictionaryField):

    @staticmethod
    def _load_json(value):
        try:
            value = json.dumps(value)
        except Exception as e:
            # Is this needed?
            print(value, e)
            pass
        return value

    # def __getattribute__(self, key):
    #     print('__getattribute__')
    #     value = super(HStoreJsonDict, self).__getattribute__(key)
    #     return _unpack_json(value)

    # def __getitem__(self, key):
    #     print('__getitem__')
    #     value = super(HStoreJsonDict, self).__getitem__(key)
    #     return _unpack_json(value)

    def __setattr__(self, key, value):
        print('__setattr__', key, value)
        value = self._load_json(value)
        return super(HStoreJsonDict, self).__setattr__(key, value)

class TestModel(models.Model):
    name = models.CharField(max_length=64)
    data = HStoreJsonDict(db_index=True)
    objects = hstore.HStoreManager()

    def __unicode__(self):
        return '%s - %s' % (self.name, self.data)

最佳答案

最后,我发现最简单的方法是 fork django-hstore 模块并将序列化/反序列化放在 DictionaryFieldget_prep_value 中()to_python() 方法 ( see here for code )。

对于其他希望在使用 Django 时从数据库中输入/检索数据的人来说,我强烈建议在 to_python() 上查看 Django 的文档。和 get_prep_value() .

关于python - Django HStore : How to override a key-value model field's __getattr__ and __setattr__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20202082/

相关文章:

python - python对象的真假标准是什么?

PYTHON - 不可哈希列表

Django CheckConstraint : Elements of reverse ForeignKey lookup must not be empty

python - Django collectstatic boot broken pipe on large file upload

json - 将 JSON 结果读取为字典数组

json - BSON数据库的简单编辑器

python - 削波 FFT 矩阵

python - 为 formset 中的每个表单提供不同的 kwargs

python - django:触发下载后重定向到另一个页面

jquery - 使用 jQuery 处理 JSON 数据 - 需要alert() 的奇怪结果