【问题标题】:How to add more than one food item per order with Django Models?如何使用 Django 模型为每个订单添加多个食品?
【发布时间】:2018-09-03 19:38:04
【问题描述】:

我正在为我兄弟的酒吧构建一个应用程序。他将接受命令并负责。我有一个“食物”和一个“订单”模型。比方说:

class Food(models.Model):
    Name = models.CharField(max_length=50)
    Price = models.DecimalField(max_digits=7, decimal_places=2)
    Stock = models.BooleanField()

class Order(models.Model):
    Date = models.DateField(auto_now=True)
    Product = models.ForeignKey(Food, on_delete=models.PROTECT, null=True, blank=True)
    Quantity = models.IntegerField()

    TotalPrice = models.DecimalField(max_digits=7, decimal_places=2)

我不知道如何在同一个订单中添加不止一种食物。还要指定每种食物的数量。

【问题讨论】:

标签: django django-models


【解决方案1】:

您的模型不在这里。您需要 三个 模型:Order、Food 和 OrderItem,这是每个订单的食品项目列表。所以:

class Food(models.Model):
    ...

class Order(models.Model):
    Date = models.DateField(auto_now=True)
    TotalPrice = models.DecimalField(max_digits=7, decimal_places=2)

class OrderItem(models.Model):
    Order = models.ForeignKey(Order, on_delete=models.PROTECT)
    Product = models.ForeignKey(Food, on_delete=models.PROTECT, null=True, blank=True)
    Quantity = models.IntegerField()

现在给定一个 Order 实例,您可以通过 my_order.orderitem_set.all() 获取项目。

(注意,通常的 Python 风格是为字段等属性使用小写名称:total_priceproductquantity。)

【讨论】:

  • 是的,是的,是的。我想这就是我要找的。我将尝试实现这一点并让你知道。谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-02
  • 2018-04-10
  • 2021-05-04
  • 2021-04-21
  • 2012-10-15
  • 1970-01-01
相关资源
最近更新 更多