GraphQL在Django中的使用教程

 更新时间:2022年12月26日 10:19:14   作者:Mr.Lee jack  
这篇文章主要介绍了GraphQL在Django中的使用教程,本文结合示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

简介

特点

  • 请求你所要的数据,不多不少
  • 获取多个资源,只用一个请求
  • 描述所有的可能,类型系统
  • 几乎所有语言支持

文档

Graphene-Python

GraphQL | A query language for your API

背景

  • 传统restful的接口定义类型多,试图简化接口定义
  • django中使用restframework定义restful资源接口时,可能会出现深度查询,造成有时候查询过度
  • 例如前端用户需要查询接口用于展示在下拉框时,用户仅需要id与value值时,造成无用字段冗余,影响接口返回性能
  • 当一张表字段较多时,例如接口1一共有40个字段,A页面需要5个字段做展示,B页面需要另外10个字段展示,这时我们需要根据用户需求定义返回接口提升性能,且数据不会被暴露

实际问题

问题

  • 请求数据量40kB可以根据用户缩减,也就是返回数据量可以做到<40KB
  • 后端数据实际耗时783ms,但是数据传输一共耗时5s
    Django中如何使用呢
    安装

安装

pip install graphene-django

django配置

INSTALLED_APPS = [
    "django.contrib.staticfiles", 
    "graphene_django"
    ]
GRAPHENE = {
    "SCHEMA": "test_api.schema.schema" # 下文中需要定义schema.py文件
}

Demo

定义数据库模型

from django.db import models


class Category(models.Model):
    name = models.CharField(max_length=100, help_text="名称")
    id = models.BigAutoField(primary_key=True)


class Ingredient(models.Model):
    id = models.BigAutoField(primary_key=True)
    name = models.CharField(max_length=100, help_text="名称")
    notes = models.TextField(help_text="笔记")
    category = models.ForeignKey(
        Category, related_name="category", on_delete=models.CASCADE
    )

    def __str__(self):
        return self.name

定义serializer

from graphene_django.rest_framework.mutation import SerializerMutation
from rest_framework.serializers import ModelSerializer

from ..models import Category, Ingredient


class CategorySerializer(ModelSerializer):
    class Meta:
        model = Category
        fields = "__all__"


class IngredientSerializer(ModelSerializer):
    class Meta:
        model = Ingredient
        fields = "__all__"

定义接口

import graphene
from graphene import relay
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from graphene_django.rest_framework.mutation import SerializerMutation

from ..models import Category, Ingredient

from ..serializer import CategorySerializer, IngredientSerializer


# 为查询添加查询总数
class CountableConnectionBase(relay.Connection):
    class Meta:
        abstract = True

    total_count = graphene.Int()

    def resolve_total_count(self, info, **kwargs):
        return self.iterable.count()


# Ingredient 查看过滤
class IngredientFilter(DjangoObjectType):
    class Meta:
        model = Ingredient
        fields = "__all__"
        filter_fields = {
            "name": ['exact', "contains", "istartswith"],
            "category": ["exact"],
            'category__name': ['exact'],
        }
        interfaces = (relay.Node,)
        connection_class = CountableConnectionBase

    extra_field = graphene.String()

    def resolve_extra_field(self: Ingredient, info):
        return "hello!" + str(self.id)


# CategoryFilter 查询过滤
class CategoryFilter(DjangoObjectType):
    class Meta:
        model = Category
        fields = "__all__"
        filter_fields = {
            "name": ['exact', "contains", "istartswith"],
        }
        interfaces = (relay.Node,)
        connection_class = CountableConnectionBase


# CategoryMutation 修改或新增
class CategoryMutation(SerializerMutation):
    class Meta:
        serializer_class = CategorySerializer


# IngredientMutation 修改或新增
class IngredientMutation(SerializerMutation):
    class Meta:
        serializer_class = IngredientSerializer


# 汇总query接口
class ApiQuery(graphene.ObjectType):
    search_category = DjangoFilterConnectionField(CategoryFilter)
    search_ingredient = DjangoFilterConnectionField(IngredientFilter)


# 汇总操作类接口
class ApiMutation(graphene.ObjectType):
    update_category = CategoryMutation.Field()
    update_ingredient = IngredientMutation.Field()

汇总所有接口

import graphene

from .api import ApiQuery, ApiMutation


class Query(ApiQuery):
    # 新增时提供多继承即可
    pass


class Mutation(ApiMutation):
    # 新增时提供多继承即可
    pass


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

启动

python manage.py runserver 0.0.0.0:8080

接口文档

总结

  • 查询时,可以使用django_filter , 快速查询
  • 用法基本和drf框架基本类似
  • 接口面涉及的深度查询,通过connection实现,如果返回字段中没有改要求,将不会深度查询

到此这篇关于GraphQL在Django中的使用教程的文章就介绍到这了,更多相关GraphQL在Django中的使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

相关文章

  • python中的全局变量与局部变量解读

    python中的全局变量与局部变量解读

    这篇文章主要介绍了python中的全局变量与局部变量用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-06-06
  • python导出hive数据表的schema实例代码

    python导出hive数据表的schema实例代码

    这篇文章主要介绍了python导出hive数据表的schema实例代码,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • 详解利用装饰器扩展Python计时器

    详解利用装饰器扩展Python计时器

    在本文中,云朵君将和大家一起了解装饰器的工作原理,如何将我们之前定义的定时器类 Timer 扩展为装饰器,以及如何简化计时功能,感兴趣的可以了解一下
    2022-06-06
  • python socket实现聊天室

    python socket实现聊天室

    这篇文章主要为大家详细介绍了python socket实现聊天室,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • 利用Python实现自制文件搜索小工具

    利用Python实现自制文件搜索小工具

    当自己电脑文件很多还有点乱,不记得自己文件放哪里的时候,用电脑自带的搜索文件,这个等待时间可慢了。所以我们不如自己用python做一个搜索工具!犄角旮旯的文件都能一秒钟搜索出来的那种
    2022-09-09
  • python Tkinter版学生管理系统

    python Tkinter版学生管理系统

    这篇文章主要为大家详细介绍了python Tkinter版学生管理系统,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-02-02
  • Python使用Flask Migrate模块迁移数据库

    Python使用Flask Migrate模块迁移数据库

    Flask-Migrate是一个为Flask应用处理SQLAlchemy数据库迁移的扩展,使得可以通过Flask的命令行接口或者Flask-Scripts对数据库进行操作
    2022-07-07
  • Python使用xlrd轻松读取Excel文件的示例代码

    Python使用xlrd轻松读取Excel文件的示例代码

    本文主要介绍了使用 Python 的 xlrd 库读取 Excel 文件的方法,包括安装、各种操作如工作表操作、单元格操作、行与列操作、处理不同数据类型、性能优化、结合其他库、自定义处理等,还提到了一些特殊情况的处理及自定义类封装读取逻辑,需要的朋友可以参考下
    2024-11-11
  • pyinstaller打包程序exe踩过的坑

    pyinstaller打包程序exe踩过的坑

    这篇文章主要介绍了pyinstaller打包exe踩过的坑,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11
  • 用十张图详解TensorFlow数据读取机制(附代码)

    用十张图详解TensorFlow数据读取机制(附代码)

    这篇文章主要介绍了用十张图详解TensorFlow数据读取机制(附代码),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02

最新评论