Matthew Johnston
Matthew Johnston

Reputation: 4439

Graphene-Django and Model Properties

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)?

Upvotes: 13

Views: 3399

Answers (1)

Yacine Filali
Yacine Filali

Reputation: 1772

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, )

Upvotes: 31

Related Questions