My Projects

Django Models

My team, The Undefined Variables, decided to make a sample ecommerce website for our Capstone/WOW Project. This is the models.py from the app. It’s only 54 Lines of code. More hours of frustration, debate went into those 54 lines than I ever possibly could have imagined. It still wasn’t perfect; I can look at this within a few seconds and see five things that I would want to change. But when working as a team we must make compromises and I often had to defer. I’m still quite proud of how it turned out. Check the whole project out here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from django.db import models

# Create your models here.
class Tag(models.Model):
type = models.CharField(max_length=30)

def __str__(self):
return self.type


# addressee indicates the recipient of the order not necessarily the person placing the order.
class Addressee(models.Model):
name = models.CharField(max_length=40)
address = models.CharField(max_length=120)
city = models.CharField(max_length=30)
state = models.CharField(max_length=2)
zipcode = models.CharField(max_length=10)

def __str__(self):
return self.name


class Product(models.Model):
types = models.ManyToManyField(Tag)
name = models.CharField(max_length=30)
description = models.CharField(max_length=200, null=True)
image = models.ImageField(null=True)
price = models.DecimalField()

def __str__(self):
return self.name


class Order(models.Model):
STATUS = (
("Pending", "Pending"),
("Out for delivery", "Out for delivery"),
("Delivered", "Delivered"),
)
addressee = models.ForeignKey(Addressee, on_delete=models.SET_NULL, null=True)
date = models.DateTimeField(auto_now_add=True)
status = models.CharField(
max_length=200, null=True, choices=STATUS, default="pending"
)

def get_order_items(self):
return self.orderitem_set.all()

def get_total(self):
orderitems = self.orderitem_set.all()
total = 0
for item in orderitems:
total += item.product.price * item.quantity
return total


class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.CASCADE)
quantity = models.IntegerField(default=0, null=True, blank=True)

def get_total(self):
total = self.product.price * self.quantity
return total