Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Change product to have exactly one category
Anna Siwike664ebc60282
diff --git a/saleor/cart/models.py b/saleor/cart/models.pyindex eb9e2ce380..ab2350dcfe 100644--- a/saleor/cart/models.py+++ b/saleor/cart/models.py@@ -71,7 +71,7 @@ class CartQueryset(models.QuerySet):problem."""return self.prefetch_related(- 'lines__variant__product__categories',+ 'lines__variant__product__category','lines__variant__product__images','lines__variant__product__product_class__product_attributes__values', # noqa'lines__variant__product__product_class__variant_attributes__values', # noqadiff --git a/saleor/cart/utils.py b/saleor/cart/utils.pyindex 0b39a76407..21f9bdef42 100644--- a/saleor/cart/utils.py+++ b/saleor/cart/utils.py@@ -77,11 +77,8 @@ def get_category_variants_and_prices(cart, root_category):products = {cart_line.variant.product for cart_line in cart.lines.all()}matching_products = set()for product in products:- for category in product.categories.all():- is_descendant = category.is_descendant_of(- root_category, include_self=True)- if is_descendant:- matching_products.add(product)+ if product.category.is_descendant_of(root_category, include_self=True):+ matching_products.add(product)for product in matching_products:for line in get_product_variants_and_prices(cart, product):yield linediff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 95063fb12b..837df91828 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -207,9 +207,9 @@ def create_products_by_class(product_class, schema,category = get_or_create_category(category_name)for dummy in range(how_many):- product = create_product(product_class=product_class)+ product = create_product(+ product_class=product_class, category=category)set_product_attributes(product, product_class)- product.categories.add(category)if create_images:class_placeholders = os.path.join(placeholder_dir, schema['images_dir'])diff --git a/saleor/dashboard/product/filters.py b/saleor/dashboard/product/filters.pyindex 904da55846..b8972b5f88 100644--- a/saleor/dashboard/product/filters.py+++ b/saleor/dashboard/product/filters.py@@ -35,9 +35,9 @@ class ProductFilter(SortedFilterSet):name = CharFilter(label=pgettext_lazy('Product list filter label', 'Name'),lookup_expr='icontains')- categories = ModelMultipleChoiceFilter(- label=pgettext_lazy('Product list filter label', 'Categories'),- name='categories',+ category = ModelMultipleChoiceFilter(+ label=pgettext_lazy('Product list filter label', 'Category'),+ name='category',queryset=Category.objects.all())product_class = ModelMultipleChoiceFilter(label=pgettext_lazy('Product list filter label', 'Product type'),diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex 56888bc094..97c960f538 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -119,7 +119,7 @@ class ProductForm(forms.ModelForm):labels = {'name': pgettext_lazy('Item name', 'Name'),'description': pgettext_lazy('Description', 'Description'),- 'categories': pgettext_lazy('Categories', 'Categories'),+ 'category': pgettext_lazy('Category', 'Category'),'price': pgettext_lazy('Currency amount', 'Price'),'available_on': pgettext_lazy('Availability date', 'Availability date'),@@ -131,8 +131,6 @@ class ProductForm(forms.ModelForm):def __init__(self, *args, **kwargs):self.product_attributes = []super().__init__(*args, **kwargs)- self.fields['categories'].widget.attrs['data-placeholder'] = (- pgettext_lazy('Product form placeholder', 'Search'))product_class = self.instance.product_classself.product_attributes = product_class.product_attributes.all()self.product_attributes = self.product_attributes.prefetch_related(diff --git a/saleor/data_feeds/google_merchant.py b/saleor/data_feeds/google_merchant.pyindex 1dde6c8c9f..e33af67ccd 100644--- a/saleor/data_feeds/google_merchant.py+++ b/saleor/data_feeds/google_merchant.py@@ -29,7 +29,7 @@ def get_feed_items():items = ProductVariant.objects.all()items = items.select_related('product')items = items.prefetch_related(- 'images', 'stock', 'product__categories',+ 'images', 'stock', 'product__category','product__images', 'product__product_class__product_attributes','product__product_class__variant_attributes')return itemsdiff --git a/saleor/discount/models.py b/saleor/discount/models.pyindex 6d19a7b174..0c218e95ce 100644--- a/saleor/discount/models.py+++ b/saleor/discount/models.py@@ -231,12 +231,9 @@ class Sale(models.Model):raise NotImplementedError('Unknown discount type')def _product_has_category_discount(self, product, discounted_categories):- for category in product.categories.all():- for discounted_category in discounted_categories:- if category.is_descendant_of(discounted_category,- include_self=True):- return True- return False+ return any([+ product.category.is_descendant_of(category, include_self=True)+ for category in discounted_categories])def modifier_for_product(self, product):discounted_products = {p.pk for p in self.products.all()}diff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex 0e68430802..ef7de67773 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -119,8 +119,8 @@ class CategoryType(DjangoObjectType):def resolve_products(self, info, **args):context = info.contextqs = products_visible_to_user(context.user)- qs = qs.prefetch_related('images', 'categories', 'variants__stock')- qs = qs.filter(categories=self)+ qs = qs.prefetch_related('images', 'category', 'variants__stock')+ qs = qs.filter(category=self)attributes_filter, order_by, price_lte, price_gte = map(args.get, ['attributes', 'order_by', 'price_lte', 'price_gte'])@@ -272,7 +272,7 @@ class Query(graphene.ObjectType):pk=category_pk).get_descendants(include_self=True)product_classes = set([obj[0] for obj in Product.objects.filter(- categories__in=tree).values_list('product_class_id')])+ category__in=tree).values_list('product_class_id')])queryset = queryset.filter(Q(products_class__in=product_classes) |Q(product_variants_class__in=product_classes))diff --git a/saleor/product/filters.py b/saleor/product/filters.pyindex 848797ce25..4c8bb632c2 100644--- a/saleor/product/filters.py+++ b/saleor/product/filters.py@@ -39,12 +39,12 @@ class ProductFilter(SortedFilterSet):product_attributes = (ProductAttribute.objects.all().prefetch_related('values')- .filter(products_class__products__categories=self.category)+ .filter(products_class__products__category=self.category).distinct())variant_attributes = (ProductAttribute.objects.all().prefetch_related('values')- .filter(product_variants_class__products__categories=self.category)+ .filter(product_variants_class__products__category=self.category).distinct())return product_attributes, variant_attributesdiff --git a/saleor/product/migrations/0046_product_category.py b/saleor/product/migrations/0046_product_category.pynew file mode 100644index 0000000000..6081bdd17d--- /dev/null+++ b/saleor/product/migrations/0046_product_category.py@@ -0,0 +1,31 @@+# -*- coding: utf-8 -*-+# Generated by Django 1.11.9 on 2018-01-16 11:56+from __future__ import unicode_literals++from django.db import migrations, models+import django.db.models.deletion+++def assign_category_to_products(apps, schema_editor):+ Product = apps.get_model('product', 'Product')+ Category = apps.get_model('product', 'Category')+ default_category = Category.objects.first()+ for product in Product.objects.all():+ product.category = product.categories.first() or default_category+ product.save()+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0045_md_to_html'),+ ]++ operations = [+ migrations.AddField(+ model_name='product',+ name='category',+ field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='product.Category'),+ ),+ migrations.RunPython(assign_category_to_products, migrations.RunPython.noop),+ ]diff --git a/saleor/product/migrations/0047_auto_20180116_0603.py b/saleor/product/migrations/0047_auto_20180116_0603.pynew file mode 100644index 0000000000..bda8ac7f5a--- /dev/null+++ b/saleor/product/migrations/0047_auto_20180116_0603.py@@ -0,0 +1,25 @@+# -*- coding: utf-8 -*-+# Generated by Django 1.11.9 on 2018-01-16 12:03+from __future__ import unicode_literals++from django.db import migrations, models+import django.db.models.deletion+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0046_product_category'),+ ]++ operations = [+ migrations.RemoveField(+ model_name='product',+ name='categories',+ ),+ migrations.AlterField(+ model_name='product',+ name='category',+ field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='products', to='product.Category'),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex fd6df30344..c06280d726 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -96,7 +96,7 @@ class Product(models.Model, ItemRange):ProductClass, related_name='products', on_delete=models.CASCADE)name = models.CharField(max_length=128)description = models.TextField()- categories = models.ManyToManyField(Category, related_name='products')+ category = models.ForeignKey(Category, related_name='products')price = PriceField(currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2)available_on = models.DateField(blank=True, null=True)@@ -146,10 +146,7 @@ class Product(models.Model, ItemRange):return any(variant.is_in_stock() for variant in self)def get_first_category(self):- for category in self.categories.all():- if not category.is_hidden:- return category- return None+ return self.category if not self.category.is_hidden else Nonedef is_available(self):today = datetime.date.today()diff --git a/saleor/product/utils.py b/saleor/product/utils.pyindex dd83772fd0..827cb897f1 100644--- a/saleor/product/utils.py+++ b/saleor/product/utils.py@@ -25,7 +25,7 @@ def products_visible_to_user(user):def products_with_details(user):products = products_visible_to_user(user)products = products.prefetch_related(- 'categories', 'images', 'variants__stock',+ 'category', 'images', 'variants__stock','variants__variant_images__image', 'attributes__values','product_class__variant_attributes__values','product_class__product_attributes__values')diff --git a/saleor/product/views.py b/saleor/product/views.pyindex 9c68230035..80587a7db7 100644--- a/saleor/product/views.py+++ b/saleor/product/views.py@@ -114,9 +114,8 @@ def category_index(request, path, category_id):if actual_path != path:return redirect('product:category', permanent=True, path=actual_path,category_id=category_id)- products = (products_with_details(user=request.user)- .filter(categories__id=category.id)- .order_by('name'))+ products = products_with_details(user=request.user).filter(+ category__id=category.id).order_by('name')product_filter = ProductFilter(request.GET, queryset=products, category=category)products_paginated = get_paginator_items(diff --git a/templates/dashboard/product/form.html b/templates/dashboard/product/form.htmlindex 2c39bf3e3f..0764038549 100644--- a/templates/dashboard/product/form.html+++ b/templates/dashboard/product/form.html@@ -91,7 +91,7 @@</div>{% endif %}<div class="row">- {{ product_form.categories|materializecss }}+ {{ product_form.category|materializecss }}</div><div class="row">{{ product_form.available_on|materializecss }}diff --git a/tests/conftest.py b/tests/conftest.pyindex d2886c4f56..4333423831 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -247,8 +247,8 @@ def product_in_stock(product_class, default_category):product = Product.objects.create(name='Test product', price=Decimal('10.00'),- product_class=product_class, attributes=attributes)- product.categories.add(default_category)+ product_class=product_class, attributes=attributes,+ category=default_category)variant_attr = product_class.variant_attributes.first()variant_attr_value = variant_attr.values.first()@@ -281,18 +281,18 @@ def product_list(product_class, default_category):product_1 = Product.objects.create(name='Test product 1', price=Decimal('10.00'),- product_class=product_class, attributes=attributes, is_published=True)- product_1.categories.add(default_category)+ product_class=product_class, attributes=attributes, is_published=True,+ category=default_category)product_2 = Product.objects.create(name='Test product 2', price=Decimal('20.00'),- product_class=product_class, attributes=attributes, is_published=False)- product_2.categories.add(default_category)+ product_class=product_class, attributes=attributes, is_published=False,+ category=default_category)product_3 = Product.objects.create(name='Test product 3', price=Decimal('20.00'),- product_class=product_class, attributes=attributes, is_published=True)- product_3.categories.add(default_category)+ product_class=product_class, attributes=attributes, is_published=True,+ category=default_category)return [product_1, product_2, product_3]@@ -334,9 +334,8 @@ def product_with_image(product_in_stock, product_image):def unavailable_product(product_class, default_category):product = Product.objects.create(name='Test product', price=Decimal('10.00'),- product_class=product_class,- is_published=False)- product.categories.add(default_category)+ product_class=product_class, is_published=False,+ category=default_category)return product@@ -344,8 +343,7 @@ def unavailable_product(product_class, default_category):def product_with_images(product_class, default_category):product = Product.objects.create(name='Test product', price=Decimal('10.00'),- product_class=product_class)- product.categories.add(default_category)+ product_class=product_class, category=default_category)file_mock_0 = MagicMock(spec=File, name='FileMock0')file_mock_0.name = 'image0.jpg'file_mock_1 = MagicMock(spec=File, name='FileMock1')@@ -366,11 +364,11 @@ def voucher(db): # pylint: disable=W0613@pytest.fixture()-def order_with_lines(order, product_class):+def order_with_lines(order, product_class, default_category):group = DeliveryGroup.objects.create(order=order)product = Product.objects.create(name='Test product', price=Decimal('10.00'),- product_class=product_class)+ product_class=product_class, category=default_category)OrderLine.objects.create(delivery_group=group,@@ -383,7 +381,7 @@ def order_with_lines(order, product_class):)product = Product.objects.create(name='Test product 2', price=Decimal('20.00'),- product_class=product_class)+ product_class=product_class, category=default_category)OrderLine.objects.create(delivery_group=group,@@ -396,7 +394,7 @@ def order_with_lines(order, product_class):)product = Product.objects.create(name='Test product 3', price=Decimal('30.00'),- product_class=product_class)+ product_class=product_class, category=default_category)OrderLine.objects.create(delivery_group=group,@@ -412,11 +410,11 @@ def order_with_lines(order, product_class):@pytest.fixture()-def order_with_lines_and_stock(order, product_class):+def order_with_lines_and_stock(order, product_class, default_category):group = DeliveryGroup.objects.create(order=order)product = Product.objects.create(name='Test product', price=Decimal('10.00'),- product_class=product_class)+ product_class=product_class, category=default_category)variant = ProductVariant.objects.create(product=product, sku='SKU_A')warehouse = StockLocation.objects.create(name='Warehouse 1')stock = Stock.objects.create(@@ -435,7 +433,7 @@ def order_with_lines_and_stock(order, product_class):)product = Product.objects.create(name='Test product 2', price=Decimal('20.00'),- product_class=product_class)+ product_class=product_class, category=default_category)variant = ProductVariant.objects.create(product=product, sku='SKU_B')stock = Stock.objects.create(variant=variant, cost_price=2, quantity=2, quantity_allocated=2,@@ -483,11 +481,11 @@ def order_with_variant_from_different_stocks(order_with_lines_and_stock):@pytest.fixture()-def delivery_group(order, product_class):+def delivery_group(order, product_class, default_category):group = DeliveryGroup.objects.create(order=order)product = Product.objects.create(name='Test product', price=Decimal('10.00'),- product_class=product_class)+ product_class=product_class, category=default_category)variant = ProductVariant.objects.create(product=product, sku='SKU_A')warehouse = StockLocation.objects.create(name='Warehouse 1')stock = Stock.objects.create(diff --git a/tests/dashboard/test_product.py b/tests/dashboard/test_product.pyindex 904b87bf49..5faea63550 100644--- a/tests/dashboard/test_product.py+++ b/tests/dashboard/test_product.py@@ -90,11 +90,12 @@ def test_variantless_product_class_form(color_attribute, size_attribute):assert not form.is_valid()-def test_edit_used_product_class(db):+def test_edit_used_product_class(db, default_category):product_class = ProductClass.objects.create(name='New class', has_variants=True)product = Product.objects.create(- name='Test product', price=10, product_class=product_class)+ name='Test product', price=10, product_class=product_class,+ category=default_category)ProductVariant.objects.create(product=product, sku='1234')# When all products have only one variant you can change@@ -143,7 +144,7 @@ def test_change_attributes_in_product_form(data = {'name': product.name,'price': product.price.gross,- 'categories': [c.pk for c in product.categories.all()],+ 'category': product.category.pk,'description': 'description','attribute-author': new_author,'attribute-color': new_color}diff --git a/tests/test_cart.py b/tests/test_cart.pyindex e6a1990a14..0dac48cab0 100644--- a/tests/test_cart.py+++ b/tests/test_cart.py@@ -699,13 +699,9 @@ def test_cart_line_state(product_in_stock, request_cart_with_item):def test_get_category_variants_and_prices(default_category, product_in_stock, request_cart_with_item):- variant = product_in_stock.variants.get()- top_category = Category.objects.create(name='foo', slug='bar')- product_in_stock.categories.add(top_category)- default_category.parent = top_category- default_category.save()result = list(utils.get_category_variants_and_prices(- request_cart_with_item, top_category))+ request_cart_with_item, default_category))+ variant = product_in_stock.variants.get()assert result[0][0] == variantdiff --git a/tests/test_discounts.py b/tests/test_discounts.pyindex a5816cb73c..23c2e0844a 100644--- a/tests/test_discounts.py+++ b/tests/test_discounts.py@@ -291,14 +291,14 @@ def test_products_voucher_checkout_discount_not(settings, monkeypatch, prices,@pytest.mark.django_db-def test_sale_applies_to_correct_products(product_class):+def test_sale_applies_to_correct_products(product_class, default_category):product = Product.objects.create(name='Test Product', price=10, description='', pk=10,- product_class=product_class)+ product_class=product_class, category=default_category)variant = ProductVariant.objects.create(product=product, sku='firstvar')product2 = Product.objects.create(name='Second product', price=15, description='',- product_class=product_class)+ product_class=product_class, category=default_category)sec_variant = ProductVariant.objects.create(product=product2, sku='secvar', pk=10)sale = Sale.objects.create(@@ -311,33 +311,6 @@ def test_sale_applies_to_correct_products(product_class):sale.modifier_for_product(sec_variant.product)-def test_get_category_variants_and_prices_product_with_many_categories(- cart, default_category, product_in_stock):- # Test: don't duplicate percentage voucher- # when product is in more than one category with discount- category = Category.objects.create(- name='Foobar', slug='foo', parent=default_category)- product_in_stock.price = Decimal('10.00')- product_in_stock.save()- product_in_stock.categories.add(category)- variant = product_in_stock.variants.first()- cart.add(variant, check_quantity=False)-- discounted_products = list(- get_category_variants_and_prices(cart, default_category))- assert len(discounted_products) == 1-- voucher = Voucher.objects.create(- category=default_category, type=VoucherType.CATEGORY,- discount_value='10.0', code='foobar',- discount_value_type=DiscountValueType.PERCENTAGE)- checkout_mock = Mock(spec=Checkout, cart=cart)- discount = voucher.get_discount_for_checkout(checkout_mock)- # 10% of 10.00 is 1.00- assert discount.amount == Price('1.00', currency=discount.amount.currency)--def test_increase_voucher_usage():voucher = Voucher.objects.create(code='unique', type=VoucherType.VALUE,diff --git a/tests/test_elasticsearch.py b/tests/test_elasticsearch.pyindex 188bc6e2fc..e9f1552609 100644--- a/tests/test_elasticsearch.py+++ b/tests/test_elasticsearch.py@@ -53,8 +53,8 @@ def indexed_products(product_class, default_category):pk=object_id,name='Test product ' + str(object_id),price=Decimal(10.0),- product_class=product_class)- product.categories.add(default_category)+ product_class=product_class,+ category=default_category)return productreturn [gen_product_with_id(prod) for prod in PRODUCTS_INDEXED]diff --git a/tests/test_postgresql_search.py b/tests/test_postgresql_search.pyindex dcb1d25694..95ee77711a 100644--- a/tests/test_postgresql_search.py+++ b/tests/test_postgresql_search.py@@ -25,8 +25,8 @@ def named_products(default_category, product_class):name=name,description=description,price=Decimal(6.6),- product_class=product_class)- product.categories.add(default_category)+ product_class=product_class,+ category=default_category)return productreturn [gen_product(name, desc) for name, desc in PRODUCTS]diff --git a/tests/test_product.py b/tests/test_product.pyindex b61e7ff7e5..23a28da5d2 100644--- a/tests/test_product.py+++ b/tests/test_product.py@@ -19,10 +19,10 @@ from saleor.product.utils import (@pytest.fixture()-def product_with_no_attributes(product_class):+def product_with_no_attributes(product_class, default_category):product = models.Product.objects.create(name='Test product', price='10.00',- product_class=product_class)+ product_class=product_class, category=default_category)return product@@ -125,20 +125,20 @@ def test_available_products_only_available(product_list):assert all([product.is_available() for product in available_products])-def test_filtering_by_attribute(db, color_attribute):+def test_filtering_by_attribute(db, color_attribute, default_category):product_class_a = models.ProductClass.objects.create(name='New class', has_variants=True)product_class_a.product_attributes.add(color_attribute)- product_class_b = models.ProductClass.objects.create(name='New class',- has_variants=True)+ product_class_b = models.ProductClass.objects.create(+ name='New class', has_variants=True)product_class_b.variant_attributes.add(color_attribute)product_a = models.Product.objects.create(- name='Test product a', price=10,- product_class=product_class_a)+ name='Test product a', price=10, product_class=product_class_a,+ category=default_category)models.ProductVariant.objects.create(product=product_a, sku='1234')product_b = models.Product.objects.create(- name='Test product b', price=10,- product_class=product_class_b)+ name='Test product b', price=10, product_class=product_class_b,+ category=default_category)variant_b = models.ProductVariant.objects.create(product=product_b,sku='12345')color = color_attribute.values.first()@@ -402,9 +402,8 @@ def test_variant_availability_status(unavailable_product):def test_product_filter_before_filtering(authorized_client, product_in_stock, default_category):- products = (models.Product.objects.all()- .filter(categories__name=default_category)- .order_by('-price'))+ products = models.Product.objects.all().filter(+ category__name=default_category).order_by('-price')url = reverse('product:category', kwargs={'path': default_category.slug,'category_id': default_category.pk})@@ -415,7 +414,7 @@ def test_product_filter_before_filtering(def test_product_filter_product_exists(authorized_client, product_in_stock,default_category):products = (models.Product.objects.all()- .filter(categories__name=default_category)+ .filter(category__name=default_category).order_by('-price'))url = reverse('product:category', kwargs={'path': default_category.slug,@@ -438,7 +437,7 @@ def test_product_filter_product_does_not_exist(def test_product_filter_form(authorized_client, product_in_stock,default_category):products = (models.Product.objects.all()- .filter(categories__name=default_category)+ .filter(category__name=default_category).order_by('-price'))url = reverse('product:category', kwargs={'path': default_category.slug,@@ -452,7 +451,7 @@ def test_product_filter_form(authorized_client, product_in_stock,def test_product_filter_sorted_by_price_descending(authorized_client, product_list, default_category):products = (models.Product.objects.all()- .filter(categories__name=default_category, is_published=True)+ .filter(category__name=default_category, is_published=True).order_by('-price'))url = reverse('product:category', kwargs={'path': default_category.slug,diff --git a/tests/test_sitemap.py b/tests/test_sitemap.pyindex e8b82334ae..6f0ac31f99 100644--- a/tests/test_sitemap.py+++ b/tests/test_sitemap.py@@ -7,10 +7,9 @@ def test_sitemap_uses_site_settings_domain(client, product_in_stock):product_url = 'http://%(domain)s%(product_url)s' % {'domain': domain,'product_url': product_in_stock.get_absolute_url()}- category = product_in_stock.categories.first()category_url = 'http://%(domain)s%(category_url)s' % {'domain': domain,- 'category_url': category.get_absolute_url()}+ 'category_url': product_in_stock.category.get_absolute_url()}expected_links = [product_url, category_url]response = client.get(reverse('django.contrib.sitemaps.views.sitemap'))