每个动态字段django模型 [英] Per instance dynamic fields django model

查看:94
本文介绍了每个动态字段django模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有JSON字段或CouchDB文档链接的模型。我现在可以通过以下方式访问动态信息提供:



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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆