Graphene Django without Django Model?

牧云@^-^@ 提交于 2019-12-08 04:50:05

问题


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


回答1:


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.




回答2:


When you map your Django model to a GraphQL, it create a new model with GraphQL object types from the introspection of the Django model.. And nothing prevent you to combine this model with with plain GraphQL objects types, or mapped from an other third party persistence model



来源:https://stackoverflow.com/questions/45789617/graphene-django-without-django-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!