[Django]-Graphene and Django about relationships

6👍

You could add a sku field and resolver to ProductNode like:

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)

Then you’ll have a sku field as part of the product response. But since what you’re asking for is to mix fields from both the Sku and the ProductSku models, you are probably better off creating a new object type that is not a model type, it’s just an ObjectType with 3 fields (id, name, price) and then dynamically returning an instance of that. So in that case you should do this for 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)

And you’d create the SkuObjectType like

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

Leave a comment