| 1 |
from django.db.models import F, Sum |
| 2 |
from django.test import TestCase |
| 3 |
|
| 4 |
from .models import Product, Stock |
| 5 |
|
| 6 |
|
| 7 |
class DecimalFieldLookupTests(TestCase): |
| 8 |
@classmethod |
| 9 |
def setUpTestData(cls): |
| 10 |
cls.p1 = Product.objects.create(name="Product1", qty_target=10) |
| 11 |
Stock.objects.create(product=cls.p1, qty_available=5) |
| 12 |
Stock.objects.create(product=cls.p1, qty_available=6) |
| 13 |
cls.p2 = Product.objects.create(name="Product2", qty_target=10) |
| 14 |
Stock.objects.create(product=cls.p2, qty_available=5) |
| 15 |
Stock.objects.create(product=cls.p2, qty_available=5) |
| 16 |
cls.p3 = Product.objects.create(name="Product3", qty_target=10) |
| 17 |
Stock.objects.create(product=cls.p3, qty_available=5) |
| 18 |
Stock.objects.create(product=cls.p3, qty_available=4) |
| 19 |
cls.queryset = Product.objects.annotate( |
| 20 |
qty_available_sum=Sum("stock__qty_available"), |
| 21 |
).annotate(qty_needed=F("qty_target") - F("qty_available_sum")) |
| 22 |
|
| 23 |
def test_gt(self): |
| 24 |
qs = self.queryset.filter(qty_needed__gt=0) |
| 25 |
self.assertCountEqual(qs, [self.p3]) |
| 26 |
|
| 27 |
def test_gte(self): |
| 28 |
qs = self.queryset.filter(qty_needed__gte=0) |
| 29 |
self.assertCountEqual(qs, [self.p2, self.p3]) |
| 30 |
|
| 31 |
def test_lt(self): |
| 32 |
qs = self.queryset.filter(qty_needed__lt=0) |
| 33 |
self.assertCountEqual(qs, [self.p1]) |
| 34 |
|
| 35 |
def test_lte(self): |
| 36 |
qs = self.queryset.filter(qty_needed__lte=0) |
| 37 |
self.assertCountEqual(qs, [self.p1, self.p2]) |