pip install graphene-django

2、生成 Django 初始代碼,編寫 models.py,編寫 GraphQL 的模式。

django-admin startproject cookbook
cd cookbook
python manage.py startapp ingredients

修改 models.py 文件,添加兩個(gè)類,一個(gè)是對(duì)應(yīng)分類,別一個(gè)對(duì)應(yīng)原料,修改后內(nèi)容如下所示:

from django.db import models

# Create your models here.

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

def __str__(self):
return self.name

class Ingredient(models.Model):
name = models.CharField(max_length=100)
notes = models.TextField()
category = models.ForeignKey(
Category, related_name="ingredients", on_delete=models.CASCADE
)

def __str__(self):
return self.name

外鍵代表兩者之間的關(guān)系:一個(gè)分類下面可以有多個(gè)原料,但一個(gè)原料只能屬于某一個(gè)分類。

然后,我們?cè)?settings.py 同一級(jí)的目錄,新增一個(gè) schema.py 文件,內(nèi)容如下:

import graphene
from graphene_django import DjangoObjectType

from ingredients.models import Category, Ingredient

class CategoryType(DjangoObjectType):
class Meta:
model = Category
fields = ("id", "name", "ingredients")

class IngredientType(DjangoObjectType):
class Meta:
model = Ingredient
fields = ("id", "name", "notes", "category")

class Query(graphene.ObjectType):
all_ingredients = graphene.List(IngredientType)
all_categorys = graphene.List(CategoryType)
category_by_name = graphene.Field(CategoryType, name=graphene.String(required=True))

def resolve_all_categorys(root, info):
return Category.objects.all()

def resolve_all_ingredients(root, info):
# We can easily optimize query count in the resolve method
return Ingredient.objects.all()

def resolve_category_by_name(root, info, name):
try:
return Category.objects.get(name=name)
except Category.DoesNotExist:
return None

schema = graphene.Schema(query=Query)

schema 是 GraphQL 的核心代碼,Query 類和 models 類很像,對(duì)比著寫代碼就可以了,后面熟悉之后再理解它的原理。

接著,我們?cè)?settings.py 的 INSTALLED_APPS 添加兩條記錄:

 "ingredients.apps.IngredientsConfig",
"graphene_django",

配置 cookbook.urls 使用剛才創(chuàng)建的 schema, 內(nèi)容如下:

from django.contrib import admin
from django.urls import path
from django.views.decorators.csrf import csrf_exempt

from graphene_django.views import GraphQLView
from cookbook.schema import schema
urlpatterns = [
path("admin/", admin.site.urls),
path("graphql/", csrf_exempt(GraphQLView.as_view(graphiql=True,schema=schema))),
]

3、建表,插入測(cè)試數(shù)據(jù)。

(py38env) ?  cookbook python manage.py makemigrations
Migrations for 'ingredients':
ingredients/migrations/0001_initial.py
- Create model Category
- Create model Ingredient
(py38env) ? cookbook python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, ingredients, sessions
Running migrations:
Applying ingredients.0001_initial... OK
(py38env) ? cookbook ls
cookbook db.sqlite3 ingredients manage.py

至此,db.sqlite3 中已經(jīng)有了兩張表,接下來插入測(cè)試數(shù)據(jù),數(shù)據(jù)來源:ingredients.json

下載后保存到項(xiàng)目的根目錄,也就是第一個(gè) cookbook 目錄下,然后執(zhí)行下面的命令導(dǎo)入測(cè)試數(shù)據(jù):

(py38env) ?  cookbook python manage.py loaddata ingredients.json 
Installed 6 object(s) from 1 fixture(s)

4、啟動(dòng)服務(wù),并測(cè)試。

python manage.py runserver

瀏覽器打開 http://localhost:8000/graphql/ 就可以看到如下頁面:

這就是 GraphQL 的接口調(diào)試界面,左邊輸入查詢條件,右邊返回?cái)?shù)據(jù)。

比如查一下所有的原料表:

query {
allIngredients {
id
name
note
}
}

接下來反著查一下,比如查詢所有的分類:

query {
allCategorys {
id
name
}
}

查詢所有的分類及對(duì)應(yīng)的原料信息:

query {
allCategorys {
id
name
ingredients{
id
name
notes
}
}
}

查詢某一分類,比如乳制品分類下面的原料信息:

query {
categoryByName(name: "Dairy") {
id
name
ingredients {
id
name
}
}
}

總結(jié)

GraphQL 非常強(qiáng)大,并且可以快速集成 Django 模型,從而可以非常方便的將你的應(yīng)用 api 轉(zhuǎn)換為 GraphQL 風(fēng)格。

文章轉(zhuǎn)自微信公眾號(hào)@Python七號(hào)

上一篇:

Django REST framework實(shí)現(xiàn)API之基礎(chǔ)篇

下一篇:

使用Rust語言快速構(gòu)建API能力開放
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)