-
Notifications
You must be signed in to change notification settings - Fork 3
/
managers.py
41 lines (29 loc) · 1.05 KB
/
managers.py
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
from django.db import models, transaction
from django.db.models.functions import Lag
class OrderQuerySet(models.QuerySet):
def unshipped(self):
return self.filter(is_shipped=False)
def diff_vs_previous_order(self):
return self.annotate(
prev_order_id=models.Window(
expression=Lag('id'),
partition_by=[models.F('customer_id')],
order_by=models.F('created_at').asc(),
)
)
class OrderManager(models.Manager):
def create_order(self, products, **kwargs):
with transaction.atomic():
# Ensure that we have enough products in inventory
for product in products:
product.purchase()
order = self.create(**kwargs)
order.lines.bulk_create([
order.lines.model(
order=order,
product=product,
gross_amount=product.price,
)
for product in products
])
return order