【问题标题】:Django: parametrizing db_table for inheritanceDjango:为继承参数化 db_table
【发布时间】:2011-01-25 12:09:38
【问题描述】:

我想在一个基类中设置db_table元类属性,这样所有继承的类都会有它们的名字,类似于Django对待related_name模型字段属性的方式:

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

所以继承模型:

class SubModel(BaseModel):
    pass

会有数据库表prefix_submodel

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

【问题讨论】:

  • 你试过了吗,还是失败了?乍一看,它看起来应该工作......
  • 当然。它在同步数据库期间引发TypeError: format requires a mapping

标签: django inheritance metaclass


【解决方案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>]

【讨论】:

  • 谢谢,djeneralize 所做的令人印象深刻。 imo,它应该在 django 的核心。但我想要的是简单地为从同一模型继承的表名设置一个前缀。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
  • 2021-02-04
  • 2019-11-17
  • 2011-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多