Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add stock queryset

Mira Szewczyk52bb3025519e
diff --git a/saleor/stock/migrations/0001_initial.py b/saleor/stock/migrations/0001_initial.py
index 994ac74e68..9956baf95b 100644
--- a/saleor/stock/migrations/0001_initial.py
+++ b/saleor/stock/migrations/0001_initial.py
@@ -1,4 +1,4 @@
-# Generated by Django 2.2.6 on 2019-11-25 12:31
+# Generated by Django 2.2.6 on 2019-11-27 11:55
import django.db.models.deletion
from django.db import migrations, models
@@ -9,8 +9,8 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
- ("product", "0110_auto_20191108_0340"),
("warehouse", "0001_initial"),
+ ("product", "0110_auto_20191108_0340"),
]
operations = [
@@ -26,8 +26,8 @@ class Migration(migrations.Migration):
verbose_name="ID",
),
),
- ("quantity", models.PositiveIntegerField()),
- ("quantity_allocated", models.PositiveIntegerField()),
+ ("quantity", models.PositiveIntegerField(default=0)),
+ ("quantity_allocated", models.PositiveIntegerField(default=0)),
(
"product_variant",
models.ForeignKey(
diff --git a/saleor/stock/models.py b/saleor/stock/models.py
index af8b888143..10193369f3 100644
--- a/saleor/stock/models.py
+++ b/saleor/stock/models.py
@@ -3,12 +3,19 @@ from django.utils.translation import pgettext_lazy
from ..core.exceptions import InsufficientStock
from ..product.models import ProductVariant
+from ..shipping.models import ShippingZone
from ..warehouse.models import Warehouse
class StockQuerySet(models.QuerySet):
- def get_stock(self, product_variant: ProductVariant, warehouse=Warehouse):
- return self.get(product_variant=product_variant, warehouse=warehouse)
+ def get_stock_for_country(self, product_variant: ProductVariant, country_code: str):
+ shipping_zone = ShippingZone.objects.prefetch_related("warehouse_set").get(
+ countries__icontains=country_code
+ )
+ return self.get(
+ warehouse=models.Subquery(shipping_zone.warehouse_set.get()),
+ product_variant=product_variant,
+ )
class Stock(models.Model):
@@ -16,8 +23,8 @@ class Stock(models.Model):
product_variant = models.ForeignKey(
ProductVariant, null=False, on_delete=models.CASCADE
)
- quantity = models.PositiveIntegerField()
- quantity_allocated = models.PositiveIntegerField()
+ quantity = models.PositiveIntegerField(default=0)
+ quantity_allocated = models.PositiveIntegerField(default=0)
objects = StockQuerySet.as_manager()
@@ -37,6 +44,10 @@ class Stock(models.Model):
def quantity_available(self) -> int:
return max(self.quantity - self.quantity_allocated, 0)
+ @property
+ def is_available(self):
+ return self.quantity > 0
+
def check_quantity(self, quantity):
if quantity > self.quantity_available:
raise InsufficientStock(self)