我是Graphene的新手,正在对其进行测试,以查看是否可以将其用于具有复杂查询的Django项目。为了测试它,我正在尝试使用以下模型创建电子商务

class Sku(models.Model):
    name = models.CharField(max_length=100)


class Product(models.Model):
    name = models.CharField(max_length=100)

class ProductSku(models.Model):
    sku = models.ForeignKey(Sku, related_name='product_sku', on_delete=models.CASCADE)
    product = models.ForeignKey(Product, related_name='product_sku', on_delete=models.CASCADE)
    price = models.IntegerField()


如您所见,在使用ProductSku模型时,Product和Sku具有多对多关系

使用Graphene的文档,我创建了以下架构

class SkuNode(DjangoObjectType):
    class Meta:
        model = Sku


class ProductNode(DjangoObjectType):
    class Meta:
        model = Product

class ProductSkuNode(DjangoObjectType):
    class Meta:
        model = ProductSku



class Query(graphene.ObjectType):
    all_products = graphene.List(ProductNode, name=graphene.String())

    product = graphene.Field(ProductNode, id=graphene.Int())

    def resolve_all_products(self, info, **args):
        name = args.get('name')
        if name is not None:
            return Product.objects.filter(name__icontains=name)
        return Product.objects.all()

    def resolve_product(self, info, **args):
        id = args.get('id')
        if id is not None:
            return Product.objects.filter(pk=id).first()


现在,我的前端应用程序可以通过执行查询来获取给定SKU的给定产品价格

query{
  allProducts{
    id,
    name,
    productSku{
      price,
      sku{
        id,
        name
      }
    }
  }
}


但是我想做的是查询SkuNode内部价格的查询

query{
  allProducts{
    id,
    name,
    sku{
      id,
      name,
      price
    }
  }
}


那有可能吗?

最佳答案

您可以向ProductNode添加sku字段和解析器,例如:

class ProductNode(DjangoObjectType):
    sku = graphene.Field(SkuNode)

    class Meta:
        model = Product

    def resolve_sku(self, info):
        return self.product_sku.sku # (however you get the Sku object from a Product instance)


然后,您将在产品响应中包含一个sku字段。但是,由于您要的是混合SkuProductSku模型中的字段,因此最好创建一个不是模型类型的新对象类型,它只是一个3的ObjectType字段(ID,名称,价格),然后动态返回该实例。因此,在这种情况下,您应该对ProductNode

class ProductNode(DjangoObjectType):
    sku = graphene.Field(SkuObjectType)

    class Meta:
        model = Product

    def resolve_sku(self, info):
        sku = self.product_sku.sku
        return SkuObjectType(id=sku.id, name=sku.name, price=self.product_sky.price)


然后您将创建SkuObjectType

class SkuNode(DjangoObjectType):
    id = graphene.ID()
    name = graphene.String()
    price = graphene.Int()

关于python - Graphene和Django有关关系的信息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53565881/

10-08 21:43