Matias Gatti
Matias Gatti

Reputation: 23

How to add more than one food item per order with Django Models?

I am building an App for my brother's Bar. He will take orders and charge. I have a 'Food' and a 'Order' model. Let's say:

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)

I cannot figure out how to add, on the same order, more than one food. Also specify quantity for each food.

Upvotes: 1

Views: 783

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

Your models aren't right here. You need three models: Order, Food, and OrderItem, which is a list of food items for each order. So:

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()

Now given an instance of Order, you would get the items by doing my_order.orderitem_set.all().

(Note, usual Python style is to have lower_case names for attributes like fields: total_price, product, quantity.)

Upvotes: 1

Related Questions