Skip to content

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

Changed attributes relations from M2O to M2M

NyanKiyoshidc612bc26835
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index b1fd0f57ed..8d207fd12e 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -165,9 +165,15 @@ def create_attributes(attributes_data):
for attribute in attributes_data:
pk = attribute["pk"]
defaults = attribute["fields"]
- defaults["product_type_id"] = defaults.pop("product_type")
- defaults["product_variant_type_id"] = defaults.pop("product_variant_type")
- Attribute.objects.update_or_create(pk=pk, defaults=defaults)
+ product_type_id = defaults.pop("product_type")
+ product_variant_type_id = defaults.pop("product_variant_type")
+ attr, _ = Attribute.objects.update_or_create(pk=pk, defaults=defaults)
+
+ if product_type_id:
+ attr.product_types.add(product_type_id)
+
+ if product_variant_type_id:
+ attr.product_variant_types.add(product_variant_type_id)
def create_attributes_values(values_data):
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index e35b70d064..3f389c005e 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -111,15 +111,17 @@ class ProductTypeForm(forms.ModelForm):
(tax.code, tax.description) for tax in manager.get_tax_rate_type_choices()
]
unassigned_attrs_q = Q(
- product_type__isnull=True, product_variant_type__isnull=True
+ product_types__isnull=True, product_variant_types__isnull=True
)
if self.instance.pk:
product_attrs_qs = Attribute.objects.filter(
- Q(product_type=self.instance) | unassigned_attrs_q
+ Q(attributeproduct__product_type_id=self.instance.pk)
+ | unassigned_attrs_q
)
variant_attrs_qs = Attribute.objects.filter(
- Q(product_variant_type=self.instance) | unassigned_attrs_q
+ Q(attributevariant__product_type_id=self.instance.pk)
+ | unassigned_attrs_q
)
product_attrs_initial = self.instance.product_attributes.all()
variant_attrs_initial = self.instance.variant_attributes.all()
diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.py
index 1fb1962cec..49eeabc1b7 100644
--- a/saleor/dashboard/product/views.py
+++ b/saleor/dashboard/product/views.py
@@ -533,14 +533,15 @@ def ajax_upload_image(request, product_pk):
@permission_required("product.manage_products")
def attribute_list(request):
attributes = Attribute.objects.prefetch_related(
- "values", "product_type", "product_variant_type"
+ "values", "product_types", "product_variant_types"
).order_by("name")
attribute_filter = AttributeFilter(request.GET, queryset=attributes)
attributes = [
(
attribute.pk,
attribute.name,
- attribute.product_type or attribute.product_variant_type,
+ list(attribute.product_types.all())
+ + list(attribute.product_variant_types.all()),
attribute.values.all(),
)
for attribute in attribute_filter.qs
@@ -560,12 +561,14 @@ def attribute_list(request):
@permission_required("product.manage_products")
def attribute_details(request, pk):
attributes = Attribute.objects.prefetch_related(
- "values", "product_type", "product_variant_type"
+ "values", "product_types", "product_variant_types"
).all()
attribute = get_object_or_404(attributes, pk=pk)
- product_type = attribute.product_type or attribute.product_variant_type
+ product_types = list(attribute.product_types.all()) + list(
+ attribute.product_variant_types.all()
+ )
values = attribute.values.all()
- ctx = {"attribute": attribute, "product_type": product_type, "values": values}
+ ctx = {"attribute": attribute, "product_types": product_types, "values": values}
return TemplateResponse(request, "dashboard/product/attribute/detail.html", ctx)
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index 20fe9c9ea1..6d659de928 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -9,7 +9,6 @@ from ...core.mutations import (
ModelMutation,
UpdateMetaBaseMutation,
)
-from ...product.types import ProductType
from ..descriptions import AttributeDescriptions, AttributeValueDescriptions
from ..types import Attribute
@@ -209,8 +208,6 @@ class AttributeUpdate(AttributeMixin, ModelMutation):
class AttributeDelete(ModelDeleteMutation):
- product_type = graphene.Field(ProductType, description="A related product type.")
-
class Arguments:
id = graphene.ID(required=True, description="ID of an attribute to delete.")
@@ -219,12 +216,6 @@ class AttributeDelete(ModelDeleteMutation):
description = "Deletes an attribute."
permissions = ("product.manage_products",)
- @classmethod
- def success_response(cls, instance):
- response = super().success_response(instance)
- response.product_type = instance.product_type or instance.product_variant_type
- return response
-
class AttributeUpdateMeta(UpdateMetaBaseMutation):
class Meta:
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index 49f0b05bca..240b67b40e 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -25,7 +25,7 @@ ATTRIBUTES_SEARCH_FIELDS = ("name", "slug")
def _filter_attributes_by_product_types(attribute_qs, product_qs):
product_types = set(product_qs.values_list("product_type_id", flat=True))
return attribute_qs.filter(
- Q(product_type__in=product_types) | Q(product_variant_type__in=product_types)
+ Q(product_types__in=product_types) | Q(product_variant_types__in=product_types)
)
diff --git a/saleor/graphql/product/types/attributes.py b/saleor/graphql/product/types/attributes.py
index 3a14fd1f62..3f18a0fbd0 100644
--- a/saleor/graphql/product/types/attributes.py
+++ b/saleor/graphql/product/types/attributes.py
@@ -82,7 +82,7 @@ class Attribute(CountableDjangoObjectType, MetadataObjectType):
description = """
Custom attribute of a product. Attributes can be
assigned to products and variants at the product type level."""
- only_fields = ["id", "product_type", "product_variant_type"]
+ only_fields = ["id", "product_types", "product_variant_types"]
interfaces = [relay.Node]
model = models.Attribute
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 64f2f5731c..351d932b36 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -143,8 +143,8 @@ type AssignNavigation {
type Attribute implements Node {
id: ID!
- productType: ProductType
- productVariantType: ProductType
+ productTypes(before: String, after: String, first: Int, last: Int): ProductTypeCountableConnection
+ productVariantTypes(before: String, after: String, first: Int, last: Int): ProductTypeCountableConnection
privateMeta: [MetaStore]!
meta: [MetaStore]!
name: String
@@ -192,7 +192,6 @@ input AttributeCreateInput {
type AttributeDelete {
errors: [Error!]
- productType: ProductType
attribute: Attribute
}
diff --git a/saleor/product/filters.py b/saleor/product/filters.py
index 27fc9e590c..6a4fe3a535 100644
--- a/saleor/product/filters.py
+++ b/saleor/product/filters.py
@@ -94,11 +94,11 @@ class ProductCategoryFilter(ProductFilter):
def _get_product_attributes_lookup(self):
categories = self.category.get_descendants(include_self=True)
- return Q(product_type__products__category__in=categories)
+ return Q(product_types__products__category__in=categories)
def _get_variant_attributes_lookup(self):
categories = self.category.get_descendants(include_self=True)
- return Q(product_variant_type__products__category__in=categories)
+ return Q(product_variant_types__products__category__in=categories)
class ProductCollectionFilter(ProductFilter):
@@ -107,7 +107,7 @@ class ProductCollectionFilter(ProductFilter):
super().__init__(*args, **kwargs)
def _get_product_attributes_lookup(self):
- return Q(product_type__products__collections=self.collection)
+ return Q(product_types__products__collections=self.collection)
def _get_variant_attributes_lookup(self):
- return Q(product_variant_type__products__collections=self.collection)
+ return Q(product_variant_types__products__collections=self.collection)
diff --git a/saleor/product/migrations/0095_migrate_attrs_to_m2m.py b/saleor/product/migrations/0095_migrate_attrs_to_m2m.py
new file mode 100644
index 0000000000..b977c4778f
--- /dev/null
+++ b/saleor/product/migrations/0095_migrate_attrs_to_m2m.py
@@ -0,0 +1,148 @@
+# Generated by Django 2.2.2 on 2019-06-12 08:15
+
+from django.db import migrations, models
+
+
+def migrate_fk_to_m2m(product_type_related_field):
+ def make_migration(apps, schema):
+ ProductType = apps.get_model("product", "ProductType")
+
+ for product_type in ProductType.objects.all():
+ m2m_field = getattr(product_type, product_type_related_field)
+ attributes_to_migrate = getattr(
+ product_type, f"{product_type_related_field}_old"
+ )
+ for attr in attributes_to_migrate.all():
+ if product_type not in m2m_field.all():
+ m2m_field.add(attr)
+
+ return make_migration
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [("product", "0094_auto_20190611_0952")]
+
+ operations = [
+ # Rename the foreign keys to backup them before overriding and processing them
+ migrations.RenameField(
+ model_name="attribute", old_name="product_type", new_name="product_type_old"
+ ),
+ migrations.RenameField(
+ model_name="attribute",
+ old_name="product_variant_type",
+ new_name="product_variant_type_old",
+ ),
+ # Rename related names of foreign keys
+ migrations.AlterField(
+ model_name="attribute",
+ name="product_type_old",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=models.deletion.CASCADE,
+ related_name="product_attributes_old",
+ to="product.ProductType",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="attribute",
+ name="product_variant_type_old",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=models.deletion.CASCADE,
+ related_name="variant_attributes_old",
+ to="product.ProductType",
+ ),
+ ),
+ # Add the M2M new fields
+ migrations.CreateModel(
+ name="AttributeProduct",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "attribute",
+ models.ForeignKey(
+ on_delete=models.deletion.CASCADE,
+ related_name="attributeproduct",
+ to="product.Attribute",
+ ),
+ ),
+ (
+ "product_type",
+ models.ForeignKey(
+ on_delete=models.deletion.CASCADE,
+ related_name="attributeproduct",
+ to="product.ProductType",
+ ),
+ ),
+ ],
+ options={"abstract": False},
+ ),
+ migrations.CreateModel(
+ name="AttributeVariant",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "attribute",
+ models.ForeignKey(
+ on_delete=models.deletion.CASCADE,
+ related_name="attributevariant",
+ to="product.Attribute",
+ ),
+ ),
+ (
+ "product_type",
+ models.ForeignKey(
+ on_delete=models.deletion.CASCADE,
+ related_name="attributevariant",
+ to="product.ProductType",
+ ),
+ ),
+ ],
+ options={"abstract": False},
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="product_types",
+ field=models.ManyToManyField(
+ blank=True,
+ related_name="product_attributes",
+ through="product.AttributeProduct",
+ to="product.ProductType",
+ ),
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="product_variant_types",
+ field=models.ManyToManyField(
+ blank=True,
+ related_name="variant_attributes",
+ through="product.AttributeVariant",
+ to="product.ProductType",
+ ),
+ ),
+ # Migrate the foreign keys into M2M
+ migrations.RunPython(migrate_fk_to_m2m("product_attributes")),
+ migrations.RunPython(migrate_fk_to_m2m("variant_attributes")),
+ # Remove the migrated foreign keys
+ migrations.RemoveField(model_name="attribute", name="product_variant_type_old"),
+ migrations.RemoveField(model_name="attribute", name="product_type_old"),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 8eca8bc1b3..be98ba1089 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -425,22 +425,40 @@ class DigitalContentUrl(models.Model):
return build_absolute_uri(url)
+class AttributeProduct(models.Model):
+ attribute = models.ForeignKey(
+ "Attribute", related_name="attributeproduct", on_delete=models.CASCADE
+ )
+ product_type = models.ForeignKey(
+ ProductType, related_name="attributeproduct", on_delete=models.CASCADE
+ )
+
+
+class AttributeVariant(models.Model):
+ attribute = models.ForeignKey(
+ "Attribute", related_name="attributevariant", on_delete=models.CASCADE
+ )
+ product_type = models.ForeignKey(
+ ProductType, related_name="attributevariant", on_delete=models.CASCADE
+ )
+
+
class Attribute(ModelWithMetadata):
slug = models.SlugField(max_length=50, unique=True)
name = models.CharField(max_length=50)
- product_type = models.ForeignKey(
+ product_types = models.ManyToManyField(
ProductType,
- related_name="product_attributes",
blank=True,
- null=True,
- on_delete=models.CASCADE,
+ related_name="product_attributes",
+ through=AttributeProduct,
+ through_fields=["attribute", "product_type"],
)
- product_variant_type = models.ForeignKey(
+ product_variant_types = models.ManyToManyField(
ProductType,
- related_name="variant_attributes",
blank=True,
- null=True,
- on_delete=models.CASCADE,
+ related_name="variant_attributes",
+ through=AttributeVariant,
+ through_fields=["attribute", "product_type"],
)
translated = TranslationProxy()
diff --git a/templates/dashboard/product/attribute/detail.html b/templates/dashboard/product/attribute/detail.html
index 9d3ea5eaec..a9eb7de67a 100644
--- a/templates/dashboard/product/attribute/detail.html
+++ b/templates/dashboard/product/attribute/detail.html
@@ -42,8 +42,12 @@
<span class="card-title">
{{ attribute.name }}
</span>
- {% if product_type %}
- {% trans "Product type" %}: <a href="{% url "dashboard:product-type-update" pk=product_type.pk %}">{{ product_type }}</a>
+ {% if product_types %}
+ {% trans "Product types" %}:
+ {% for product_type in product_types %}
+ <a href="{% url "dashboard:product-type-update" pk=product_type.pk %}">{{ product_type }}</a>
+ {% if not forloop.last %},{% endif %}
+ {% endfor %}
{% elif attribute.pk %}
<a href="{% url "dashboard:product-type-list" %}">Assign to a product type</a>
{% endif %}
diff --git a/templates/dashboard/product/attribute/list.html b/templates/dashboard/product/attribute/list.html
index 10504e61b6..ce3c41fb4e 100644
--- a/templates/dashboard/product/attribute/list.html
+++ b/templates/dashboard/product/attribute/list.html
@@ -41,20 +41,20 @@
<tr>
{% trans "Name" context "Dashboard attributes list table header name" as label %}
{% sorting_header 'name' label %}
- <th>{% trans "Product type" context "Name of product type related to the attribute" %}</th>
+ <th>{% trans "Product types" context "Name of product types related to the attribute" %}</th>
<th>
{% trans "Values" context "Dashboard attributes list table header values" %}
</th>
</tr>
</thead>
<tbody>
- {% for pk, name, product_type, values in attributes %}
+ {% for pk, name, product_types, values in attributes %}
<tr data-action-go="{% url 'dashboard:attribute-details' pk=pk %}">
<td>
{{ name }}
</td>
<td>
- {{ product_type|default:'-' }}
+ {{ product_types|join:","|default:'-' }}
</td>
<td>
{% if values %}{{ values|join:", " }}{% else %}-{% endif %}
diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.py
index 81ddc6097c..7f5d0364bb 100644
--- a/tests/api/test_attributes.py
+++ b/tests/api/test_attributes.py
@@ -130,7 +130,8 @@ def test_attributes_in_category_query(user_api_client, product):
def test_attributes_in_collection_query(user_api_client, sale):
product_types = set(sale.products.all().values_list("product_type_id", flat=True))
expected_attrs = Attribute.objects.filter(
- Q(product_type__in=product_types) | Q(product_variant_type__in=product_types)
+ Q(attributeproduct__product_type_id__in=product_types)
+ | Q(attributevariant__product_type_id__in=product_types)
)
query = """
@@ -173,8 +174,12 @@ CREATE_ATTRIBUTES_QUERY = """
name
slug
}
- productType {
- id
+ productTypes(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
}
}
}
@@ -203,7 +208,7 @@ def test_create_attribute_and_attribute_values(
attribute_name
), "The default slug should be the slugified name"
assert (
- data["attribute"]["productType"] is None
+ data["attribute"]["productTypes"]["edges"] == []
), "The attribute should not have been assigned to a product type"
# Check if the attribute values were correctly created
@@ -312,8 +317,12 @@ UPDATE_ATTRIBUTE_QUERY = """
name
slug
}
- productType {
- id
+ productTypes(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
}
}
}
@@ -336,7 +345,7 @@ def test_update_attribute_name(
attribute.refresh_from_db()
data = content["data"]["attributeUpdate"]
assert data["attribute"]["name"] == name == attribute.name
- assert data["attribute"]["productType"] is None
+ assert data["attribute"]["productTypes"]["edges"] == []
def test_update_attribute_remove_and_add_values(
@@ -464,9 +473,6 @@ def test_delete_attribute(
attribute {
id
}
- productType {
- name
- }
}
}
"""
@@ -477,7 +483,7 @@ def test_delete_attribute(
)
content = get_graphql_content(response)
data = content["data"]["attributeDelete"]
- assert data["productType"]["name"] == attribute.product_type.name
+ assert data["attribute"]["id"] == variables["id"]
with pytest.raises(attribute._meta.model.DoesNotExist):
attribute.refresh_from_db()
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index 725378b9ab..30d8282286 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -247,9 +247,8 @@ def test_products_query_with_filter_attributes(
product_type = ProductType.objects.create(
name="Custom Type", has_variants=True, is_shipping_required=True
)
- attribute = Attribute.objects.create(
- slug="new_attr", name="Attr", product_type=product_type
- )
+ attribute = Attribute.objects.create(slug="new_attr", name="Attr")
+ attribute.product_types.add(product_type)
attr_value = AttributeValue.objects.create(
attribute=attribute, name="First", slug="first"
)