поле атрибутов не разрешено и всегда возвращает ноль

Я практикуюсь в моделях и схемах продуктов продавца, чтобы быть знакомыми с ariadne, где я мог получить список продуктов, но не мог получить атрибуты, связанные с продуктом. Их схема следующая

schema.graphql

type Product implements Node {
  id: ID!,
  productType: ProductType!
  name: String!
  slug: String!
  description: String!
  category: Category!
  price: Money
  attributes: [SelectedAttribute]
  variants: [ProductVariant]
  images: [ProductImage]
  collections: [Collection]
}
type SelectedAttribute {
  attribute: Attribute
  values: [AttributeValue]
}
type Attribute implements Node {
  id: ID!
  productTypes(before: String, after: String, first: Int, last: Int): ProductTypeCountableConnection!
  productVariantTypes(before: String, after: String, first: Int, last: Int): ProductTypeCountableConnection!
  inputType: AttributeInputTypeEnum
  name: String
  slug: String
  values: [AttributeValue]
  valueRequired: Boolean!
}
type AttributeValue implements Node {
  id: ID!
  name: String
  slug: String
  inputType: AttributeInputTypeEnum
}

resolvers.py

query = QueryType()

@query.field('products')
@convert_kwargs_to_snake_case
def resolve_products(obj, info, **args):
    products = models.Product.objects.all()
    if 'sort_by' not in args:
        args['sort_by'] = {
            'field': category_sorting_field.values['NAME'],
            'direction': category_direction.values['DESC']
        }
    return connection_from_queryset_slice(products, args)

product = ObjectType('Product')

@product.field('productType')
def resolve_product_type(obj, info):
    return models.ProductType.objects.get(products__id=obj.id)



@product.field('attributes')
def resolve_attributes(obj, info):
    attributes = obj.product_type.product_attributes.all()
    attributeValues = models.AttributeValue.objects.none()
    for attribute in attributes:
        attributeValues |=  models.AttributeValue.objects.filter(attribute=attribute)
    return {
        'attribute': attributes,
        'values': attributeValues
    }

Здесь тип продукта определяется с помощью @product.field('productType'), но не атрибутов. Я продолжаю получать

"attributes": [
   {
     "attribute": null
   },
   {
     "attribute": null
   }
 ]

Так выглядит модель

models.py

class Product(models.Model):
    product_type = models.ForeignKey(ProductType, related_name="products", on_delete=models.CASCADE)
    name = models.CharField(max_length=128)
    slug = models.SlugField()
    description = models.TextField(blank=True)

class BaseAssignedAttribute(models.Model):
    assignment = None
    values = models.ManyToManyField("AttributeValue")

class AssignedProductAttribute(BaseAssignedAttribute):
    """Associate a product type attribute and selected values to a given product."""

    product = models.ForeignKey(
        Product, related_name="attributes", on_delete=models.CASCADE
    )
    assignment = models.ForeignKey("AttributeProduct", on_delete=models.CASCADE, related_name="productassignments")

class AttributeProduct(SortableModel):
    attribute = models.ForeignKey("Attribute", related_name="attributeproduct", on_delete=models.CASCADE)
    product_type = models.ForeignKey(ProductType, related_name="attributeproduct", on_delete=models.CASCADE)
    assigned_products = models.ManyToManyField(
        Product,
        blank=True,
        through=AssignedProductAttribute,
        through_fields=("assignment", "product"),
        related_name="attributesrelated",
    )

class Attribute(ModelWithMetadata):
    slug = models.SlugField(max_length=250, unique=True, allow_unicode=True)
    name = models.CharField(max_length=255)

    input_type = models.CharField(
        max_length=50,
        choices=AttributeInputType.CHOICES,
        default=AttributeInputType.DROPDOWN,
    )

    product_types = models.ManyToManyField(
        ProductType,
        blank=True,
        related_name="product_attributes",
        through=AttributeProduct,
        through_fields=("attribute", "product_type"),
    )

class AttributeValue(SortableModel):
    name = models.CharField(max_length=250)
    value = models.CharField(max_length=100, blank=True, default="")
    slug = models.SlugField(max_length=255, allow_unicode=True)
    attribute = models.ForeignKey(Attribute, related_name="values", on_delete=models.CASCADE)

этот attributes = obj.product_type.product_attributes.all() дает attributes <AttributeQuerySet [<Attribute: Color>, <Attribute: Size>]> но при запросе на игровой площадке graphql возвращается значение null.

Как разрешить поле атрибутов, которое возвращает атрибут определенного продукта и значения (AttributeValue)?

0 ответов

Другие вопросы по тегам