确定合适的子类以在Python中存储特定类型的数据

时间:2014-03-28 11:34:46

标签: python django inheritance

我有一组通用属性(例如字符串和整数类型),我想使用以下django模型来存储它们:

class Attribute(models.Model):
    item            = models.ForeignKey('Item')

    class Meta:
        abstract = True

    @staticmethod
    def get_subclass_by_type(type):
        TEXT_TYPES = ["text", "string"]
        INTEGER_TYPES = ["integer", "number"]
        if type in TEXT_TYPES: 
            return TextAttribute
        if type in INTEGER_TYPES:
            return IntegerAttribute

class TextAttribute(Attribute):
    value            = models.CharField(max_length=128)

class IntegerAttribute(Attribute):
    value            = models.IntegerField()

有没有干净的&简单的方法我错过了直接定义子类中的类型?类似的东西:

class Attribute(models.Model):
    item            = models.ForeignKey('Item')

    class Meta:
        abstract = True

    @staticmethod
    def get_subclass_by_type(type):
        <do something>

class TextAttribute(Attribute):
    TYPES            = ["text", "string"]
    value            = models.CharField(max_length=128)

class IntegerAttribute(Attribute):
    TYPES            = ["integer", "number"]
    value            = models.IntegerField()

1 个答案:

答案 0 :(得分:1)

您可以尝试定义方法get_subclass_by_type,如下所示

@classmethod def get_subclass_by_type(cls, type): for subcls in cls.__subclasses__(): if type in subcls.TYPE: return subcls

尚未测试此代码,但我认为它应该有效。