Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graphene Django without Django Model?

I've successfully used Graphene-Django to successfully build several GraphQL calls. In all of those cases I populated, in whole or in part, a Django model and then returned the records I populated.

Now I have a situation where I'd like to return some data that I don't wish to store in the Django model. Is this possible to do with Graphene?

Robert

like image 844
Robert_LY Avatar asked Aug 21 '17 05:08

Robert_LY


1 Answers

Robert_LY answered his own question perfectly in the comments, I'd just like to expand his solution.

My database-less model WordForm is generated automatically, without storing it in a database. I define it as a Django model as follows:

from django.db import models
class WordForm(models.Model):
    value = models.CharField(max_length=100)
    attributes = models.CharField(max_length=100)

In the schema I define the node and query like this:

class WordFormNode(DjangoObjectType):
    class Meta:
        model = WordForm
        interfaces = (relay.Node, )

class Query(AbstractType):
    word_forms = List(WordFormNode,query=String(),some_id=String())

    def resolve_word_forms(self, args, context, info):
        query= args['query']
        some_id = from_global_id(args['some_id'])[1]
        word_forms = []
        # some logic to make WordForm objects with
        # WordForm(value=value,attributes=attributes),
        # then append them to list word_forms
        return word_forms

You can pass as many arguments as you like to the List and access them in resolve_word_forms.

like image 121
Pigmalijonas Avatar answered Oct 16 '22 14:10

Pigmalijonas