Skip to content

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

Add query to get product image by ID

Marcin Gębala1fea6684efcb
diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.py
index 35da9e744f..067c881d79 100644
--- a/saleor/graphql/product/types.py
+++ b/saleor/graphql/product/types.py
@@ -1,6 +1,7 @@
import graphene
from graphene import relay
from graphene_django.filter import DjangoFilterConnectionField
+from graphql.error import GraphQLError
from ...product import models
from ...product.templatetags.product_images import get_thumbnail
@@ -12,6 +13,7 @@ from ..core.decorators import permission_required
from ..core.filters import DistinctFilterSet
from ..core.types.common import CountableDjangoObjectType
from ..core.types.money import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
+from ..utils import get_database_id
from .filters import ProductFilterSet
@@ -144,6 +146,11 @@ class Product(CountableDjangoObjectType):
description='List of product attributes assigned to this product.')
purchase_cost = graphene.Field(MoneyRange)
margin = graphene.Field(Margin)
+ image_by_id = graphene.Field(
+ lambda: ProductImage,
+ id=graphene.Argument(
+ graphene.ID, description='ID of a product image.'),
+ description='Get a single product image by ID')
class Meta:
description = """Represents an individual item for sale in the
@@ -181,6 +188,14 @@ class Product(CountableDjangoObjectType):
_, margin = get_product_costs_data(self)
return Margin(margin[0], margin[1])
+ def resolve_image_by_id(self, info, id):
+ pk = get_database_id(info, id, ProductImage)
+ try:
+ return self.images.get(pk=pk)
+ except models.ProductImage.DoesNotExist:
+ raise GraphQLError(
+ "Could not resolve to a node with the global id of '%s'." % id)
+
class ProductType(CountableDjangoObjectType):
products = DjangoFilterConnectionField(
@@ -276,10 +291,3 @@ class ProductImage(CountableDjangoObjectType):
if size:
return get_thumbnail(self.image, size, 'crop')
return self.image.url
-
-
-class VariantImage(CountableDjangoObjectType):
- class Meta:
- description = 'Represents a variant image'
- interfaces = [relay.Node]
- model = models.VariantImage
diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.py
index 3ddc0994ad..d404c6246a 100644
--- a/saleor/graphql/utils.py
+++ b/saleor/graphql/utils.py
@@ -12,6 +12,15 @@ from .core.types.common import PermissionDisplay
registry = get_global_registry()
+def get_database_id(info, node_id, only_type):
+ """Get a database ID from a node ID of given type."""
+ _type, _id = graphene.relay.Node.from_global_id(node_id)
+ graphene_type = info.schema.get_type(_type).graphene_type
+ if graphene_type != only_type:
+ raise AssertionError('Must receive a %s id.' % only_type._meta.name)
+ return _id
+
+
def get_node(info, id, only_type=None):
"""Return node or throw an error if the node does not exist."""
node = graphene.Node.get_node_from_global_id(info, id, only_type=only_type)