简体   繁体   English

没有Django模型的石墨烯Django?

[英]Graphene Django without Django Model?

I've successfully used Graphene-Django to successfully build several GraphQL calls. 我已经成功使用Graphene-Django成功构建了几个GraphQL调用。 In all of those cases I populated, in whole or in part, a Django model and then returned the records I populated. 在所有这些情况下,我全部或部分填充Django模型,然后返回填充的记录。

Now I have a situation where I'd like to return some data that I don't wish to store in the Django model. 现在,我想返回一些我不想存储在Django模型中的数据。 Is this possible to do with Graphene? 这可能与石墨烯有关吗?

Robert 罗伯特

Robert_LY answered his own question perfectly in the comments, I'd just like to expand his solution. Robert_LY在评论中完美地回答了他自己的问题,我想扩展他的解决方案。

My database-less model WordForm is generated automatically, without storing it in a database. 我的无数据库模型WordForm是自动生成的,而无需将其存储在数据库中。 I define it as a Django model as follows: 我将其定义为Django模型,如下所示:

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. 您可以根据需要将任意数量的参数传递给列表,并在resolve_word_forms中访问它们。

当您将Django模型映射到GraphQL时,它会从Django模型的内省中创建具有GraphQL对象类型的新模型。没有什么可以阻止您将此模型与普通GraphQL对象类型结合使用,或者从其他第三方映射而来持久性模型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM