Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Make ProductVariant a base variant class; add SKU and price fields in Product
Marcin Gębalaaeaeae480135
diff --git a/saleor/product/migrations/0006_auto_20150616_0647.py b/saleor/product/migrations/0006_auto_20150616_0647.pynew file mode 100644index 0000000000..9ae7fde575--- /dev/null+++ b/saleor/product/migrations/0006_auto_20150616_0647.py@@ -0,0 +1,76 @@+# -*- coding: utf-8 -*-+from __future__ import unicode_literals++from django.db import models, migrations+from decimal import Decimal+import django_prices.models+import django.core.validators+import satchless.item+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0005_auto_20150616_0354'),+ ]++ operations = [+ migrations.CreateModel(+ name='ProductVariant',+ fields=[+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),+ ('name', models.CharField(max_length=100, verbose_name='name')),+ ('sku', models.CharField(unique=True, max_length=32, verbose_name='SKU')),+ ('price', django_prices.models.PriceField(decimal_places=4, currency=b'USD', max_digits=12, blank=True, null=True, verbose_name='price')),+ ],+ bases=(models.Model, satchless.item.Item),+ ),+ migrations.RemoveField(+ model_name='genericproduct',+ name='price',+ ),+ migrations.RemoveField(+ model_name='genericvariant',+ name='id',+ ),+ migrations.RemoveField(+ model_name='genericvariant',+ name='name',+ ),+ migrations.RemoveField(+ model_name='genericvariant',+ name='product',+ ),+ migrations.RemoveField(+ model_name='genericvariant',+ name='sku',+ ),+ migrations.AddField(+ model_name='genericproduct',+ name='stock',+ field=models.IntegerField(default=Decimal('1'), verbose_name='stock', validators=[django.core.validators.MinValueValidator(0)]),+ ),+ migrations.AddField(+ model_name='product',+ name='price',+ field=django_prices.models.PriceField(default=0, currency=b'USD', verbose_name='price', max_digits=12, decimal_places=4),+ preserve_default=False,+ ),+ migrations.AddField(+ model_name='product',+ name='sku',+ field=models.CharField(default='', unique=True, max_length=32, verbose_name='SKU'),+ preserve_default=False,+ ),+ migrations.AddField(+ model_name='productvariant',+ name='product',+ field=models.ForeignKey(related_name='variants', to='product.Product'),+ ),+ migrations.AddField(+ model_name='genericvariant',+ name='productvariant_ptr',+ field=models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, default='', serialize=False, to='product.ProductVariant'),+ preserve_default=False,+ ),+ ]diff --git a/saleor/product/models/__init__.py b/saleor/product/models/__init__.pyindex bc45cb9fe1..46810f2cb7 100644--- a/saleor/product/models/__init__.py+++ b/saleor/product/models/__init__.py@@ -1,7 +1,7 @@from .base import Category, Productfrom .discounts import FixedProductDiscount, get_product_discounts-from .products import (GenericProduct, GenericVariant, PhysicalProduct)-from .variants import (StockedProduct, ProductVariant)+from .products import (GenericProduct, GenericVariant, PhysicalProduct,+ ProductVariant, StockedProduct)from .images import ProductImage__all__ = ['Category', 'Product', 'FixedProductDiscount',diff --git a/saleor/product/models/base.py b/saleor/product/models/base.pyindex 5ee131be22..c13bc04219 100644--- a/saleor/product/models/base.py+++ b/saleor/product/models/base.py@@ -1,15 +1,19 @@from __future__ import unicode_literals+from django.conf import settingsfrom django.core.urlresolvers import reversefrom django.utils.encoding import python_2_unicode_compatible, smart_textfrom django.db import modelsfrom django.utils.text import slugifyfrom django.utils.translation import pgettext_lazy+from django_prices.models import PriceFieldfrom model_utils.managers import InheritanceManagerfrom mptt.models import MPTTModel-from satchless.item import ItemRange+from satchless.item import ItemRange, Itemfrom unidecode import unidecode+from .discounts import get_product_discounts+@python_2_unicode_compatibleclass Category(MPTTModel):@@ -38,12 +42,17 @@ class Category(MPTTModel):class Product(models.Model, ItemRange):name = models.CharField(pgettext_lazy('Product field', 'name'), max_length=128)- categories = models.ManyToManyField(- Category, verbose_name=pgettext_lazy('Product field', 'categories'),- related_name='products')+ sku = models.CharField(+ pgettext_lazy('Product field', 'SKU'), max_length=32, unique=True)description = models.TextField(verbose_name=pgettext_lazy('Product field', 'description'))collection = models.CharField(db_index=True, max_length=100, blank=True)+ categories = models.ManyToManyField(+ Category, verbose_name=pgettext_lazy('Product field', 'categories'),+ related_name='products')+ price = PriceField(pgettext_lazy('Product field', 'price'),+ currency=settings.DEFAULT_CURRENCY, max_digits=12,+ decimal_places=4)objects = InheritanceManager()@@ -53,7 +62,8 @@ class Product(models.Model, ItemRange):def __iter__(self):if self.variants.exists():if not hasattr(self, '__variants'):- setattr(self, '__variants', self.variants.all())+ setattr(self, '__variants',+ self.variants.select_subclasses().all())return iter(getattr(self, '__variants'))else:return iter([self])@@ -76,17 +86,85 @@ class Product(models.Model, ItemRange):def get_formatted_price(self, price):return "{0} {1}".format(price.gross, price.currency)+ def get_price_per_item(self, item, discounts=None, **kwargs):+ price = self.price+ if discounts:+ discounts = list(get_product_discounts(self, discounts, **kwargs))+ if discounts:+ modifier = max(discounts)+ price += modifier+ return price+def admin_get_price_min(self):price = self.get_price_range().min_pricereturn self.get_formatted_price(price)+admin_get_price_min.short_description = pgettext_lazy('Product admin page', 'Minimum price')def admin_get_price_max(self):price = self.get_price_range().max_pricereturn self.get_formatted_price(price)+admin_get_price_max.short_description = pgettext_lazy('Product admin page', 'Maximum price')def is_available(self):+ if self.variants.exists():+ return any(variant.is_item_available() for variant in self)+ else:+ return self.is_item_available()++ def is_item_available(self):+ raise NotImplementedError()+++@python_2_unicode_compatible+class ProductVariant(models.Model, Item):+ name = models.CharField(pgettext_lazy('Variant field', 'name'),+ max_length=100)+ sku = models.CharField(pgettext_lazy('Product field', 'SKU'), max_length=32,+ unique=True)+ price = PriceField(pgettext_lazy('Product field', 'price'),+ currency=settings.DEFAULT_CURRENCY, max_digits=12,+ decimal_places=4, blank=True, null=True)+ product = models.ForeignKey(Product, related_name='variants')++ objects = InheritanceManager()++ class Meta:+ app_label = 'product'++ def __str__(self):+ return self.product.name++ def get_price_per_item(self, discounts=None, **kwargs):+ if self.price is not None:+ price = self.price+ else:+ price = self.product.price+ if discounts:+ discounts = list(get_product_discounts(self, discounts, **kwargs))+ if discounts:+ modifier = max(discounts)+ price += modifier+ return price++ def get_absolute_url(self):+ slug = self.product.get_slug()+ product_id = self.product.id+ return reverse('product:details',+ kwargs={'slug': slug, 'product_id': product_id})++ def as_data(self):+ return {+ 'product_name': str(self),+ 'product_id': self.product.pk,+ 'variant_id': self.pk,+ 'unit_price': str(self.get_price_per_item().gross)}++ def is_shipping_required(self):+ return True++ def is_item_available(self):return Falsediff --git a/saleor/product/models/discounts.py b/saleor/product/models/discounts.pyindex feb1c70d64..503ac3aef3 100644--- a/saleor/product/models/discounts.py+++ b/saleor/product/models/discounts.py@@ -7,8 +7,6 @@ from django.utils.encoding import python_2_unicode_compatiblefrom django_prices.models import PriceFieldfrom prices import FixedDiscount-from .base import Product-class NotApplicable(ValueError):pass@@ -17,7 +15,7 @@ class NotApplicable(ValueError):@python_2_unicode_compatibleclass FixedProductDiscount(models.Model):name = models.CharField(max_length=255)- products = models.ManyToManyField(Product, blank=True)+ products = models.ManyToManyField('Product', blank=True)discount = PriceField(pgettext_lazy('Discount field', 'discount value'),currency=settings.DEFAULT_CURRENCY,max_digits=12, decimal_places=4)diff --git a/saleor/product/models/products.py b/saleor/product/models/products.pyindex 896e4a44d2..87efeebe6a 100644--- a/saleor/product/models/products.py+++ b/saleor/product/models/products.py@@ -1,19 +1,16 @@from __future__ import unicode_literals+from decimal import Decimal-from django.conf import settings+from django.core.validators import MinValueValidatorfrom django.db import modelsfrom django.utils.translation import pgettext_lazy-from django_prices.models import PriceField+from satchless.item import StockedItem-from .base import Product-from .variants import (ProductVariant, StockedProduct)+from .base import Product, ProductVariantclass PhysicalProduct(models.Model):weight = models.DecimalField(max_digits=6, decimal_places=2)- price = PriceField(- pgettext_lazy('Product field', 'price'),- currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=4)class Meta:abstract = True@@ -25,23 +22,30 @@ class PhysicalProduct(models.Model):except AttributeError:return self.product.weight- def is_available(self):- if self.variants.exists():- return any(variant.is_available() for variant in self)- else:- return False+class StockedProduct(models.Model, StockedItem):+ stock = models.IntegerField(pgettext_lazy('Product item field', 'stock'),+ validators=[MinValueValidator(0)],+ default=Decimal(1))-class GenericProduct(PhysicalProduct, Product):+ class Meta:+ abstract = True+ app_label = 'product'++ def get_stock(self):+ return self.stock++ def is_item_available(self):+ return self.get_stock() > 0+++class GenericProduct(StockedProduct, PhysicalProduct, Product):class Meta:app_label = 'product'-class GenericVariant(ProductVariant, StockedProduct):- product = models.ForeignKey(GenericProduct, related_name='variants')- name = models.CharField(pgettext_lazy('Variant field', 'name'),- max_length=100)+class GenericVariant(StockedProduct, ProductVariant):class Meta:app_label = 'product'diff --git a/saleor/product/models/variants.py b/saleor/product/models/variants.pydeleted file mode 100644index c6724509ea..0000000000--- a/saleor/product/models/variants.py+++ /dev/null@@ -1,76 +0,0 @@-from __future__ import unicode_literals-from decimal import Decimal--from django.core.validators import MinValueValidator-from django.db import models-from django.utils.translation import pgettext_lazy-from satchless.item import Item, StockedItem-from django.core.urlresolvers import reverse-from django.utils.encoding import python_2_unicode_compatible--from .discounts import get_product_discounts---class StockedProduct(models.Model, StockedItem):- stock = models.IntegerField(pgettext_lazy('Product item field', 'stock'),- validators=[MinValueValidator(0)],- default=Decimal(1))-- class Meta:- abstract = True- app_label = 'product'-- def get_stock(self):- return self.stock-- def is_available(self):- return self.get_stock() > 0---@python_2_unicode_compatible-class ProductVariant(models.Model, Item):- sku = models.CharField(- pgettext_lazy('Product field', 'SKU'), max_length=32, unique=True)- # override the price attribute to implement per-variant pricing- price = None-- class Meta:- abstract = True- app_label = 'product'-- def __str__(self):- return self.product.name-- def get_price_per_item(self, discounts=None, **kwargs):- if self.price is not None:- price = self.price- else:- price = self.product.price- if discounts:- discounts = list(get_product_discounts(self, discounts, **kwargs))- if discounts:- modifier = max(discounts)- price += modifier- return price-- def get_weight(self):- try:- return self.weight- except AttributeError:- return self.product.weight-- def get_absolute_url(self):- slug = self.product.get_slug()- product_id = self.product.id- return reverse(- 'product:details', kwargs={'slug': slug, 'product_id': product_id})-- def as_data(self):- return {- 'product_name': str(self),- 'product_id': self.product.pk,- 'variant_id': self.pk,- 'unit_price': str(self.get_price_per_item().gross)}-- def is_shipping_required(self):- return Truediff --git a/utils/create_random_data.py b/utils/create_random_data.pyindex 5bde76340f..d91b05b6b6 100644--- a/utils/create_random_data.py+++ b/utils/create_random_data.py@@ -33,6 +33,8 @@ def create_product(**kwargs):defaults = {'name': fake.company(),'price': fake.pyfloat(2, 2, positive=True),+ 'sku': fake.random_int(1, 100000),+ 'stock': fake.random_int(),'collection': collection,'weight': fake.random_digit(),'description': '\n\n'.join(fake.paragraphs(5))@@ -47,6 +49,7 @@ def create_variant(product, **kwargs):'name': fake.word(),'stock': fake.random_int(),'sku': fake.random_int(1, 100000),+ 'price': fake.pyfloat(2, 2, positive=True),'product': product}defaults.update(kwargs)@@ -78,8 +81,9 @@ def create_items(placeholder_dir, how_many=10):product.categories.add(default_category)create_product_images(product, random.randrange(1, 5), placeholder_dir)- if random.choice([True, False]):- create_variant(product)+ for _ in range(random.randrange(1, 5)):+ if random.choice([True, False]):+ create_variant(product)yield "Product - %s %s Variants" % (product, product.variants.count())