python - 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}"
解决方案
推荐阅读
- kotlin - 如何退出 Kotlinc 命令行编译器
- reactjs - 将 props 传递给 React 的无状态组件时换行
- ruby-on-rails - Rails 5 - 设计 - Heroku NoMethodError
- google-chrome - GOOGLE 错误:要从您的在线存储中选择一个项目,请登录
- firebase - 如何在不提及特定集合名称的情况下从 fire-store 文档集合数据中检索数据?
- node.js - Windows 中的节点启动错误
- c# - 从客户端到 WCF 服务的语言
- c# - 在只有 .NET 4.0 的服务器上运行 EF 5
- sorting - T-SQL:按列排序,并非每一行都包含数据
- mysql - 如何在一组字符串上添加反引号