0

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

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

所以继承模型:

class SubModel(BaseModel):
    pass

将有分贝表prefix_submodel

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

4

1 回答 1

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>]
于 2011-01-25T14:29:31.783 回答