Graphene-Django and Model Properties
Asked Answered
D

1

13

Presume a Django model similar to this:

  class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.PROTECT)
    name = models.CharField(max_length=255)
    other_alias = models.CharField(blank=True,null=True,max_length=255)

    @property
    def profile_name(self):
        if self.other_alias:
            return self.other_alias
        else:
            return self.name

I'm using Graphene-Django with this project, and I successfully created a schema to describe the Profile type, and can access it properly through a GraphQL query. However, I can't see any way that I can make that property available too.

Is the presumption that I should remove all property-style logic from my Django models, and instead only use GraphQL with the raw information in the model, and then do that logic instead in the place that I use the GraphQL data (eg. in the React app that uses it)?

Drilling answered 22/3, 2017 at 22:19 Comment(0)
J
30

In the schema object for Profile, you can add a String field with a source:

class Profile(DjangoObjectType):
    profile_name = graphene.String(source='profile_name')
    class Meta:
        model = ProfileModel
        interfaces = (relay.Node, )
Jacquerie answered 23/3, 2017 at 5:32 Comment(1)
This saved me SOOO much time. Thanks!Avictor

© 2022 - 2024 — McMap. All rights reserved.