每个动态字段django模型 [英] Per instance dynamic fields django model
问题描述
genericdocument.objects.get(pk = 1)== genericdocument.json_field ['sample subfield']我想要genericdocument.sample_subfield
以保持与项目当前共享的所有应用程序的兼容性。
** UPDATE **
这非常接近我想要实现的: http://pypi.python.org/pypi/eav-django/1.0.0 ,而是使用Django标准字段。
此问题帮助我找到解决方案:如何在Python中覆盖__getattr__而不会破坏默认行为?
class GenericDocument (models.Model):
def __getattr __(self,name):
dat a = self.get_couchdb_data()
如果data.keys()中的名称:
返回数据[name]
else:
raise AttributeError
get_couchdb_data()返回的字典作为模型实例的属性公开。
I have a model with a JSON field or a link to a CouchDB document. I can currently access the dynamic informaction in a way such as:
genericdocument.objects.get(pk=1) == genericdocument.json_field['sample subfield'] instead I would like genericdocument.sample_subfield
to maintain compatibility with all the apps the project currently shares.
** UPDATE ** This is very close to what I'm trying to achieve: http://pypi.python.org/pypi/eav-django/1.0.0 but using Django standard fields instead.
This question helped me find the solution: How do I override __getattr__ in Python without breaking the default behavior?
class GenericDocument(models.Model):
def __getattr__(self, name):
data = self.get_couchdb_data()
if name in data.keys():
return data[name]
else:
raise AttributeError
The dictionary returned by get_couchdb_data() is exposed as attributes of the model instance.
这篇关于每个动态字段django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!