Django:参数化db_table继承

时间:2011-01-25 12:09:38

标签: django inheritance metaclass

我想在基类中设置db_table Meta类属性,以便所有继承的类都有其名称,类似于Django如何处理related_name模型字段属性:

class BaseModel(models.Model):
    class Meta:
        db_table = 'prefix_%(class)s'

所以继承的模型:

class SubModel(BaseModel):
    pass

将拥有db table prefix_submodel

这可能吗? Meta类可以访问继承类的模型名称吗?

1 个答案:

答案 0 :(得分:1)

没有。你不能这样做。为多个类存储相同的表并不是那么简单。

您需要的可能是djeneralize项目。

来自示例:

class Fruit(BaseGeneralizedModel):
   name = models.CharField(max_length=30)

   def __unicode__(self):
       return self.name

class Apple(Fruit):
   radius = models.IntegerField()

   class Meta:
       specialization = 'apple'

class Banana(Fruit):
   curvature = models.DecimalField(max_digits=3, decimal_places=2)

   class Meta:
       specialization = 'banana'

class Clementine(Fruit):
   pips = models.BooleanField(default=True)

   class Meta:
       specialization = 'clementine'

which then allows the following queries to be executed:

>>> Fruit.objects.all() # what we've got at the moment
[<Fruit: Rosy apple>, <Fruit: Bendy banana>, <Fruit: Sweet
clementine>]
>>> Fruit.specializations.all() # the new stuff!
[<Apple: Rosy apple>, <Banana: Bendy banana>, <Clementine: Sweet
clementine>]