graphene-django的简单示例

1、所需要的安装包:

  graphene 2.1.8 Django 3.0.8  graphene-django 2.11.0

2、创建一个model

from django.db import models

# Create your models here.

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)
    gender = models.CharField(max_length=100)

3、app下建立一个schema文件

import graphene
from .models import User
from graphene import relay
from graphene_django import DjangoObjectType, DjangoConnectionField

class UserType(DjangoObjectType):

    class Meta:
        model = User
        interfaces = (relay.Node,)


class UserInput(graphene.InputObjectType):
    name = graphene.String(required=True)
    gender = graphene.String(required=True)


class CreateUser(graphene.Mutation):
    # a输入
    class Arguments:
        user_data = UserInput(required=True)

    # 响应
    ok = graphene.Boolean()
    user = graphene.Field(UserType)

    def mutate(self, info, user_data):
        user = User.objects.create(name=user_data['name'], gender=user_data['gender'])
        ok = True
        return CreateUser(user=user, ok=ok)


class Query(graphene.ObjectType):
    users = graphene.List(UserType)
    all_users = DjangoConnectionField(UserType)

    def resolve_users(self, info):
        return User.objects.all()

4、项目目录新建schema文件

import graphene
import MyGraph.schema


class Query(MyGraph.schema.Query):
    pass


class Mutations(graphene.ObjectType):
    create_user = MyGraph.schema.CreateUser.Field()


schema = graphene.Schema(query=Query, mutation=Mutations)

5、配置url

from django.contrib import admin
from django.urls import path
from graphene_django.views import GraphQLView

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r"graphql", GraphQLView.as_view(graphiql=True))
]

6、settings修改

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'graphene_django',
    'MyGraph'
]

  

GRAPHENE = {
    'SCHEMA': 'MyFirstGraph.schema.schema'
}

7、项目目录大致如图:

graphene-django的简单示例_第1张图片

 

 8、运行django,访问http://127.0.0.1:8000/graphql

9、添加一条数据

graphene-django的简单示例_第2张图片

 

 10、查询一条数据

graphene-django的简单示例_第3张图片

 

 

 

 

  

你可能感兴趣的:(graphene-django的简单示例)