gpt4 book ai didi

python - Django ORM 继承 : You are trying to add a non-nullable field 'dish_ptr' to [. ..] 没有默认值

转载 作者:行者123 更新时间:2023-12-05 03:54:28 24 4
gpt4 key购买 nike

我正在开发一个餐厅应用程序(并且是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com