Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 234
Matthew Johnston Avatar asked Mar 22 '17 22:03

Matthew Johnston


People also ask

What is Django Graphene?

Graphene-Django is built on top of Graphene. Graphene-Django provides some additional abstractions that make it easy to add GraphQL functionality to your Django project. First time? We recommend you start with the installation guide to get set up and the basic tutorial.

What is Graphene in GraphQL?

Graphene is a library that provides tools to implement a GraphQL API in Python using a code-first approach. Compare Graphene's code-first approach to building a GraphQL API with schema-first approaches like Apollo Server (JavaScript) or Ariadne (Python).


1 Answers

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, )
like image 114
Yacine Filali Avatar answered Oct 05 '22 12:10

Yacine Filali