How to implement EAV in Django

I need to implement a fairly standard entity-attribute-value hierarchy. There are devices of multiple types, each type has a bunch of settings it can have, each individual device has a set of particular values for each setting. It seems that both django-eav and eav-django packages are no longer maintained, so I guess I need to roll my own. But how do I architect this? So far, I am thinking something like this (skipping a lot of detail)

class DeviceType(Model):
    name = CharField()

class Device(Model):
    name = CharField()
    type = ForeignKey(DeviceType)

class Setting(Model):
    name = CharField()
    type = CharField(choices=(('Number', 'int'), ('String', 'str'), ('Boolean', 'bool')))
    device_type = ForeignKey(DeviceType)

class Value(Model):
    device = ForeignKey(Device)
    setting = ForeignKey(Setting)
    value = CharField()

    def __setattr__(self, name, value):
        if name == 'value':
            ... do validation based on the setting type ...

    def __getattr__(self, name):
        if name == 'value':
            ... convert string to whatever is the correct value for the type ...

Am I missing something? Is there a better way of doing this? Will this work?


I am trying to answer,let me know, wheather we are on a same plane. I think, you need to formulate EAV database scema first. For that identify what are the entities,attributes, and the associated values. Here, in the example mentioned by you, entity maybe device and it's attribute maybe setting. If we take other example, say in case of car sales, entity is sales recipt, attribute is product purchased by the customer(car), and values are price, car model, car colour etc. Make master tables and tables that stores mappings if any. This schema implementation in models.py will make your models, and insert values in those models through shell, or insert script.

链接地址: http://www.djcxy.com/p/25380.html

上一篇: 如何为相关对象创建自定义管理器?

下一篇: 如何在Django中实现EAV