通过模块,我一直在使用Django的hstore来弄湿我的脚。使用hstore的一个巨大优点是它允许将键值存储在字段中,同时在Postgresql中提供良好的索引。django-hstore (和一般的hstore )的一个很大的缺点是,您只能将值存储为字符串。
为了克服这一问题,我认为最好重写模型字段(hstore.DictionaryField),以便输入到该字段的任何数据都自动用JSON编码,并且从JSON中自动解码检索到的任何数据。我试图通过重写__setattr__方法来做到这一点,但是这会导致大量错误(当字段的所有属性都被设置时)。有什么正确的方法吗?
到目前为止,我已经做了些什么(我已经评论掉了getter的部分,而专注于setter,但留下它来展示我的想法):
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)https://stackoverflow.com/questions/20202082
复制相似问题