首页 > 解决方案 > Django ORM:添加父类并从子类访问其类变量

问题描述

我正在开发一个餐厅应用程序(并且是 Django/Python 的新手)。我想要一个class Dish包含一些计数器或 ID 的父级,该计数器或 ID 会随着Dish. 这些实例是具有不同特征的比萨、意大利面等菜肴。我尝试过Dish抽象和非抽象,但每次都会遇到不同的问题。

这是我的 Dish 类(为了使其抽象,我尝试了 InheritanceManager(),但在那里遇到了一些复杂情况,这让我认为这对于我的简单目的来说太过分了。非抽象的,一直给我You are trying to add a non-nullable field 'pasta_ptr',然后是IntegrityError: UNIQUE constraint failed):

class Dish(models.Model):
  #objects = InheritanceManager()
  counter = models.PositiveIntegerField(default=0)

  class Meta:
        abstract = True

这是一个子类的示例——我希望每个面食条目在菜单上都有自己的 Dish-ID 或计数器——就像 Python 中的类属性一样。如何从子类访问和实现它?如果Dish不是抽象的,我可以使用(& 访问)Dish 的主键将每道菜与我想要的 ID 联系起来吗?

class Pasta(Dish):
  #Dish.counter +=1
  name = models.CharField(max_length=64, primary_key=True)
  price = models.DecimalField(max_digits=6, decimal_places=2)

  def __str__(self):
    return f"{self.name}, price: ${self.price}"

标签: pythondjangodjango-modelsorm

解决方案


推荐阅读