作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在开发一个餐厅应用程序(并且是 Django/Python 的新手)。我想要一个父类 Dish,它将包含一些计数器或 ID,该计数器或 ID 会随着 Dish 子类的每个实例而递增。这些实例是具有不同特征和关系的比萨饼、意大利面等菜肴。我试图使 Dish
具体化,因为在那种情况下我认为我只是访问 Dish
的 PK,这将为每个菜单项提供一个 Dish-ID。但是,我不知道如何正确修复我遇到的错误:You are trying to add a non-nullable field 'pasta_ptr'
。
以下是相关的代码片段:
class Dish(models.Model):
pass # should automatically generate PK, right?
class Pasta(Dish):
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}"
class Pizza(Dish):
sizestyle = models.CharField(max_length=4, choices=SIZESTYLE_CHOICES, default=SMALL_REGULAR)
topping_count = models.IntegerField(default=0, validators=[MaxValueValidator(5), MinValueValidator(0)])
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return f"Price for {self.sizestyle} pizza with {self.topping_count} toppings: ${self.price}"
class Sub(Dish):
name = models.CharField(max_length=64, primary_key=True)
price_category = models.ForeignKey(SubPrice, on_delete=models.DO_NOTHING, related_name="sub_price_category")
def __str__(self):
return f"{self.name}, Price Category: {self.price_category}"
class Platter(Dish):
name = models.CharField(max_length=64, primary_key=True)
price_large = models.DecimalField(max_digits=6, decimal_places=2, default=0)
price_small = models.DecimalField(max_digits=6, decimal_places=2, default=0)
def __str__(self):
return f"{self.name} price: Large ${self.price_large}, Small ${self.price_small}"
最佳答案
如果您想从 Dish()
继承但数据库中没有它,您可以这样做:Django abstract base class docs
class Dish(models.Model):
# your model structure
class Meta:
abstract = True
class Pizza(Dish):
# your model structure
当您使用它时,这只会继承 Dish 中的任何内容。您不会将 Dish 视为数据库中的表。
如果您确实想将它用作父类,则需要告诉子类 Dish 是父类:django many to one docs
class Dish(models.Model):
pass
class Pizza(models.Model):
dish = models.ForeignKey(Dish, on_delete=models.CASCADE)
# other model structure
这会在数据库中为 Dish 创建一个 id,当创建 Pizza 时,它将引用 Dish 的 id (pk)。
关于python - Django ORM 继承 : You are trying to add a non-nullable field 'dish_ptr' to [. ..] 没有默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60964816/
我是一名优秀的程序员,十分优秀!