Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add optimization for product-related types
Marcin Gębala6246700b1e8e
diff --git a/saleor/graphql/core/fields.py b/saleor/graphql/core/fields.pyindex 8dc6a1f805..ba516ba1e1 100644--- a/saleor/graphql/core/fields.py+++ b/saleor/graphql/core/fields.py@@ -1,4 +1,5 @@import graphene+from django.db.models.query import QuerySetfrom django_measurement.models import MeasurementFieldfrom django_prices.models import MoneyField, TaxedMoneyFieldfrom graphene_django.converter import convert_django_field@@ -32,7 +33,12 @@ class PrefetchingConnectionField(DjangoConnectionField):def resolve_connection(cls, connection, default_manager, args, iterable):if iterable is None:iterable = default_manager- _len = iterable.count()++ if isinstance(iterable, QuerySet):+ _len = iterable.count()+ else:+ _len = len(iterable)+connection = connection_from_list_slice(iterable,args,diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.pyindex 1ae3fea4f1..79833c198a 100644--- a/saleor/graphql/core/types/common.py+++ b/saleor/graphql/core/types/common.py@@ -1,6 +1,7 @@import decimalimport graphene+import graphene_django_optimizer as gql_optimizerfrom graphene_django import DjangoObjectTypefrom saleor.core.permissions import MODELS_PERMISSIONSfrom saleor.graphql.core.utils import str_to_enum@@ -49,6 +50,12 @@ class CountableDjangoObjectType(DjangoObjectType):super().__init_subclass_with_meta__(*args, connection=countable_conn, **kwargs)+ @classmethod+ def get_node(cls, info, id):+ qs = cls._meta.model.objects.filter(pk=id)+ qs = gql_optimizer.query(qs, info)+ return qs[0] if qs else None+class Error(graphene.ObjectType):field = graphene.String(diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.pyindex 65261eb89c..05afdba8bd 100644--- a/saleor/graphql/product/resolvers.py+++ b/saleor/graphql/product/resolvers.py@@ -4,7 +4,6 @@ from django.db.models import Sum, Qfrom ...order import OrderStatusfrom ...product import models-from ...product.utils import products_visible_to_userfrom ..utils import filter_by_query_param, filter_by_period, get_database_idfrom .types import Category, ProductVariant, StockAvailability@@ -15,15 +14,15 @@ ATTRIBUTES_SEARCH_FIELDS = ('name', 'slug')def resolve_attributes(info, category_id, query):- queryset = models.Attribute.objects.prefetch_related('values')- queryset = filter_by_query_param(queryset, query, ATTRIBUTES_SEARCH_FIELDS)+ qs = models.Attribute.objects.all()+ qs = filter_by_query_param(qs, query, ATTRIBUTES_SEARCH_FIELDS)if category_id:# Get attributes that are used with product types# within the given category.category = graphene.Node.get_node_from_global_id(info, category_id, Category)if category is None:- return queryset.none()+ return qs.none()tree = category.get_descendants(include_self=True)product_types = {obj[0]@@ -32,29 +31,29 @@ def resolve_attributes(info, category_id, query):queryset = queryset.filter(Q(product_type__in=product_types)| Q(product_variant_type__in=product_types))- return queryset+ return gql_optimizer.query(qs, info)def resolve_categories(info, query, level=None):- queryset = models.Category.objects.all()+ qs = models.Category.objects.all()if level is not None:- queryset = queryset.filter(level=level)- return filter_by_query_param(queryset, query, CATEGORY_SEARCH_FIELDS)+ qs = qs.filter(level=level)+ qs = filter_by_query_param(qs, query, CATEGORY_SEARCH_FIELDS)+ return gql_optimizer.query(qs, info)def resolve_collections(info, query):user = info.context.user- if user.has_perm('product.manage_products'):- qs = models.Collection.objects.all()- else:- qs = models.Collection.objects.public()- return filter_by_query_param(qs, query, COLLECTION_SEARCH_FIELDS)+ qs = models.Collection.objects.visible_to_user(user)+ qs = filter_by_query_param(qs, query, COLLECTION_SEARCH_FIELDS)+ return gql_optimizer.query(qs, info)def resolve_products(info, category_id, stock_availability, query):user = info.context.user- qs = products_visible_to_user(user=user)+ qs = models.Product.objects.visible_to_user(user)qs = filter_by_query_param(qs, query, PRODUCT_SEARCH_FIELDS)+if category_id is not None:category = graphene.Node.get_node_from_global_id(info, category_id, Category)@@ -73,18 +72,20 @@ def resolve_products(info, category_id, stock_availability, query):return gql_optimizer.query(qs, info)-def resolve_product_types():- return models.ProductType.objects.all()+def resolve_product_types(info):+ qs = models.ProductType.objects.all()+ return gql_optimizer.query(qs, info)def resolve_product_variants(info, ids=None):- queryset = models.ProductVariant.objects.all()+ # fixme: add visible_to_user for variants+ qs = models.ProductVariant.objects.all()if ids:db_ids = [get_database_id(info, node_id, only_type=ProductVariant)for node_id in ids]- queryset = queryset.filter(pk__in=db_ids)- return queryset+ qs = qs.filter(pk__in=db_ids)+ return gql_optimizer.query(qs, info)def resolve_report_product_sales(info, period):diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.pyindex 793be44441..8f0ea6d6bb 100644--- a/saleor/graphql/product/types.py+++ b/saleor/graphql/product/types.py@@ -2,13 +2,13 @@ import reimport grapheneimport graphene_django_optimizer as gql_optimizer+from django.db.models import Prefetchfrom graphene import relayfrom graphql.error import GraphQLErrorfrom ...product import modelsfrom ...product.templatetags.product_images import get_thumbnail-from ...product.utils import (- products_with_details, calculate_revenue_for_variant)+from ...product.utils import calculate_revenue_for_variantfrom ...product.utils.availability import get_availabilityfrom ...product.utils.costs import (get_margin_for_variant, get_product_costs_data)@@ -42,21 +42,25 @@ class StockAvailability(graphene.Enum):OUT_OF_STOCK = 'OUT_OF_STOCK'-def resolve_attribute_list(attributes):+def resolve_attribute_list(attributes_hstore, attributes_qs):+ """Resolve attributes dict into a list of `SelectedAttribute`s.keys = list(attributes.keys())values = list(attributes.values())- attributes_map = {- att.pk: att for att in models.Attribute.objects.filter(- pk__in=keys)}- values_map = {- val.pk: val for val in models.AttributeValue.objects.filter(- pk__in=values)}+ `attributes_qs` is the queryset of attribute objects. If it's prefetch+ beforehand along with the values, it saves database queries.+ """+ attributes_map = {}+ values_map = {}+ for attr in attributes_qs:+ attributes_map[attr.pk] = attr+ for val in attr.values.all():+ values_map[val.pk] = valattributes_list = [SelectedAttribute(attribute=attributes_map.get(int(k)),value=values_map.get(int(v)))- for k, v in attributes.items()]+ for k, v in attributes_hstore.items()]return attributes_list@@ -89,8 +93,10 @@ class AttributeValue(CountableDjangoObjectType):class Attribute(CountableDjangoObjectType):name = graphene.String(description=AttributeDescriptions.NAME)slug = graphene.String(description=AttributeDescriptions.SLUG)- values = graphene.List(- AttributeValue, description=AttributeDescriptions.VALUES)+ values = gql_optimizer.field(+ graphene.List(+ AttributeValue, description=AttributeDescriptions.VALUES),+ model_field='values')class Meta:description = """Custom attribute of a product. Attributes can be@@ -150,8 +156,11 @@ class ProductVariant(CountableDjangoObjectType):def resolve_stock_quantity(self, info):return self.quantity_available+ @gql_optimizer.resolver_hints(+ prefetch_related='product__product_type__variant_attributes__values')def resolve_attributes(self, info):- return resolve_attribute_list(self.attributes)+ attributes_qs = self.product.product_type.variant_attributes.all()+ return resolve_attribute_list(self.attributes, attributes_qs)def resolve_margin(self, info):return get_margin_for_variant(self)@@ -247,15 +256,20 @@ class Product(CountableDjangoObjectType):def resolve_url(self, info):return self.get_absolute_url()- @gql_optimizer.resolver_hints(prefetch_related='variants', only=['available_on', 'charge_taxes', 'tax_rate'])+ @gql_optimizer.resolver_hints(+ prefetch_related='variants',+ only=['available_on', 'charge_taxes', 'price', 'tax_rate'])def resolve_availability(self, info):context = info.contextavailability = get_availability(self, context.discounts, context.taxes, context.currency)return ProductAvailability(**availability._asdict())+ @gql_optimizer.resolver_hints(+ prefetch_related='product_type__product_attributes__values')def resolve_attributes(self, info):- return resolve_attribute_list(self.attributes)+ attributes_qs = self.product_type.product_attributes.all()+ return resolve_attribute_list(self.attributes, attributes_qs)@permission_required('product.manage_products')def resolve_purchase_cost(self, info):@@ -278,19 +292,29 @@ class Product(CountableDjangoObjectType):def resolve_images(self, info, **kwargs):return self.images.all()- @gql_optimizer.resolver_hints(model_field='variants')def resolve_variants(self, info, **kwargs):return self.variants.all()- @gql_optimizer.resolver_hints(prefetch_related='product_type')- def resolve_product_type(self, info, **kwargs):- return self.product_type++def prefetch_products_for_user(info, *args, **kwargs):+ user = info.context.user+ qs = models.Product.objects.visible_to_user(user)+ return Prefetch(+ 'products', queryset=gql_optimizer.query(qs, info),+ to_attr='products_visible_to_user')class ProductType(CountableDjangoObjectType):- products = PrefetchingConnectionField(- Product,- description='List of products of this type.')+ products = gql_optimizer.field(+ PrefetchingConnectionField(+ Product, description='List of products of this type.'),+ prefetch_related=prefetch_products_for_user)+ product_attributes = gql_optimizer.field(+ PrefetchingConnectionField(Attribute),+ model_field='product_attributes')+ variant_attributes = gql_optimizer.field(+ PrefetchingConnectionField(Attribute),+ model_field='variant_attributes')tax_rate = TaxRateType(description='A type of tax rate.')variant_attributes = graphene.List(Attribute, description='Variant attributes of that product type.')@@ -303,9 +327,15 @@ class ProductType(CountableDjangoObjectType):interfaces = [relay.Node]model = models.ProductType+ def resolve_product_attributes(self, info, **kwargs):+ return self.product_attributes.all()++ def resolve_variant_attributes(self, info, **kwargs):+ return self.variant_attributes.all()+def resolve_products(self, info, **kwargs):- user = info.context.user- return products_with_details(user=user).filter(product_type=self)+ # products_visible_to_user is set by prefetch_products_for_user+ return self.products_visible_to_userdef resolve_variant_attributes(self, info):return self.variant_attributes.prefetch_related('values')@@ -315,8 +345,10 @@ class ProductType(CountableDjangoObjectType):class Collection(CountableDjangoObjectType):- products = PrefetchingConnectionField(- Product, description='List of collection products.')+ products = gql_optimizer.field(+ PrefetchingConnectionField(+ Product, description='List of collection products.'),+ prefetch_related=prefetch_products_for_user)background_image = graphene.Field(Image)class Meta:@@ -329,8 +361,8 @@ class Collection(CountableDjangoObjectType):return self.background_image or Nonedef resolve_products(self, info, **kwargs):- user = info.context.user- return products_with_details(user=user).filter(collections=self)+ # products_visible_to_user is set by prefetch_products_for_user+ return self.products_visible_to_userclass Category(CountableDjangoObjectType):@@ -369,10 +401,11 @@ class Category(CountableDjangoObjectType):return self.get_absolute_url()def resolve_products(self, info, **kwargs):- qs = models.Product.objects.available_products()- categories_tree = self.get_descendants(include_self=True)- qs = qs.filter(category__in=categories_tree)- return qs.distinct()+ # FIXME: optimize products connection+ # FIXME: include products from subcategories+ # categories_tree = self.get_descendants(include_self=True)+ # qs = qs.filter(category__in=categories_tree)+ return self.products.visible_to_user(info.request.user).all()class ProductImage(CountableDjangoObjectType):diff --git a/saleor/graphql/shipping/types.py b/saleor/graphql/shipping/types.pyindex cc90b661ab..d6dc86802a 100644--- a/saleor/graphql/shipping/types.py+++ b/saleor/graphql/shipping/types.py@@ -3,7 +3,6 @@ import decimalimport graphenefrom graphene import relayfrom graphene.types import Scalar-from graphene_django import DjangoObjectTypefrom measurement.measures import Weightfrom ...core.weight import convert_weight, get_default_weight_unit@@ -16,7 +15,7 @@ ShippingMethodTypeEnum = graphene.Enum([(code.upper(), code) for code, name in ShippingMethodType.CHOICES])-class ShippingMethod(DjangoObjectType):+class ShippingMethod(CountableDjangoObjectType):type = ShippingMethodTypeEnum(description='Type of the shipping method.')class Meta:diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 2b729160d1..27e0275af2 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -97,12 +97,21 @@ class ProductType(models.Model):class ProductQuerySet(models.QuerySet):+def available_products(self):today = datetime.date.today()return self.filter(Q(available_on__lte=today) | Q(available_on__isnull=True),Q(is_published=True))+ def visible_to_user(self, user):+ has_access_to_all = (+ user.is_authenticated and user.is_active and+ user.has_perm('products.manage_products'))+ if has_access_to_all:+ return self.all()+ return self.available_products()+class Product(SeoModel):product_type = models.ForeignKey(@@ -423,9 +432,18 @@ class VariantImage(models.Model):class CollectionQuerySet(models.QuerySet):+def public(self):return self.filter(is_published=True)+ def visible_to_user(self, user):+ has_access_to_all = (+ user.is_authenticated and user.is_active and+ user.has_perm('products.manage_products'))+ if has_access_to_all:+ return self.all()+ return self.public()+class Collection(SeoModel):name = models.CharField(max_length=128, unique=True)