Creating order models

You will need a model to store the order details, and a second model to store items bought, including their price and quantity. Edit the models.py file of the orders application and add the following code to it:

from django.db import models
from shop.models import Product

class Order(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
address = models.CharField(max_length=250)
postal_code = models.CharField(max_length=20)
city = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)

class Meta:
ordering = ('-created',)

def __str__(self):
return 'Order {}'.format(self.id)

def get_total_cost(self):
return sum(item.get_cost() for item in self.items.all())


class OrderItem(models.Model):
order = models.ForeignKey(Order,
related_name='items',
on_delete=models.CASCADE)
product = models.ForeignKey(Product,
related_name='order_items',
on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField(default=1)

def __str__(self):
return '{}'.format(self.id)

def get_cost(self):
return self.price * self.quantity

The Order model contains several fields to store customer information and a paid boolean field, which defaults to False. Later on, we are going to use this field to differentiate between paid and unpaid orders. We also define a get_total_cost() method to obtain the total cost of the items bought in this order.

The OrderItem model allows us to store the product, quantity, and price paid for each item. We include get_cost() to return the cost of the item.

Run the next command to create initial migrations for the orders application:

python manage.py makemigrations

You will see the following output:

Migrations for 'orders':
orders/migrations/0001_initial.py
- Create model Order
- Create model OrderItem

Run the following command to apply the new migration:

python manage.py migrate

Your order models are now synced to the database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset