2.Basic Tutorial基础教程

Graphene Django has a number of additional features that are designed to make working with Django easy. Our primary focus in this tutorial is to give a good understanding of how to connect models from Django ORM to Graphene object types.

Graphene Django有许多附加的特性,这些特性旨在使Django的使用更加容易。在本教程中,我们主要关注的是如何将Django ORM模型连接到Graphene对象类型。

Set up the Django project 建立Django项目

We will set up the project, create the following:

我们将设置项目,创建以下内容:

  • A Django project called cookbook
  • 一个名为的cookbookDjango项目
  • An app within cookbook called ingredients
  • cookbook项目下一个名为 ingredients的应用程序
# Create the project directory
# 创建项目目录
mkdir cookbook
cd cookbook

# Create a virtualenv to isolate our package dependencies locally
#创建一个virtualenv来在本地隔离包依赖关系
virtualenv env
source env/bin/activate  # On Windows use `env\Scripts\activate`

# Install Django and Graphene with Django support
#使用Django支持安装Django和Graphene
pip install django graphene_django

# Set up a new project with a single application
#使用单个应用程序设置新项目
django-admin startproject cookbook .  # Note the trailing '.' character
cd cookbook
django-admin startapp ingredients

Now sync your database for the first time:

现在第一次同步数据库:

python manage.py migrate

Let’s create a few simple models...

让我们创建几个简单的模型...

Defining our models 定义我们的模型

Let’s get started with these models:

让我们从这些模型开始:

# cookbook/ingredients/models.py
from django.db import models

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

Add ingredients as INSTALLED_APPS:

ingredients添加到INSTALLED_APPS

# cookbook/settings.py

INSTALLED_APPS = [
    ...
    # Install the ingredients app
    # 安装配料应用程序
    "cookbook.ingredients",
]

Don’t forget to create & run migrations:

不要忘记创建和运行迁移:

python manage.py makemigrations
python manage.py migrate

Load some test data 加载一些测试数据

Now is a good time to load up some test data. The easiest option will be to download the ingredients.json fixture and place it in cookbook/ingredients/fixtures/ingredients.json. You can then run the following:

现在是加载一些测试数据的好时机。最简单的选择是下载 ingredients.json固定并放在cookbook/ingredients/fixtures/ingredients.json. 然后可以运行以下命令:

python manage.py loaddata ingredients

Installed 6 object(s) from 1 fixture(s)

Alternatively you can use the Django admin interface to create some data yourself. You’ll need to run the development server (see below), and create a login for yourself too (python manage.py createsuperuser).

或者,您可以使用Django管理接口自己创建一些数据。您需要运行开发服务器(见下文),并为自己创建一个登录名(python manage.py createsuperuser)。

Register models with admin panel:

向管理面板注册模型:

# cookbook/ingredients/admin.py
from django.contrib import admin
from cookbook.ingredients.models import Category, Ingredient

admin.site.register(Category)
admin.site.register(Ingredient)

Hello GraphQL - Schema and Object Types 你好GraphQL-模式和对象类型

In order to make queries to our Django project, we are going to need few things:

为了对Django项目进行查询,我们需要以下几点:

  • Schema with defined object types
  • 已定义对象类型的架构
  • A view, taking queries as input and returning the result
  • 视图,将查询作为输入并返回结果

GraphQL presents your objects to the world as a graph structure rather than a more hierarchical structure to which you may be accustomed. In order to create this representation, Graphene needs to know about each type of object which will appear in the graph.

GraphQL将您的对象作为一个图结构呈现给世界,而不是一个您可能习惯的更具层次结构的结构。为了创建这种表示,Graphene需要知道将出现在图形中的每种类型对象。

This graph also has a root type through which all access begins. This is the Query class below.

此图还具有一个根类型,所有访问都通过它开始。这是下面的Query类。

To create GraphQL types for each of our Django models, we are going to subclass the DjangoObjectType class which will automatically define GraphQL fields that correspond to the fields on the Django models.

为了为每个Django模型创建GraphQL类型,我们要将DjangoObjectType类分类,该类将自动定义对应于Django模型上的字段的GraphQL字段。

After we’ve done that, we will list those types as fields in the Query class.

完成后,我们将把这些类型作为Query类中的字段列出。

Create cookbook/schema.py and type the following:

创建 cookbook/schema.py 并键入以下内容:

# cookbook/schema.py
import graphene
from graphene_django import DjangoObjectType

from cookbook.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)
    category_by_name = graphene.Field(CategoryType, name=graphene.String(required=True))

    def resolve_all_ingredients(root, info):
        # We can easily optimize query count in the resolve method
        # 我们可以很容易地在resolve方法中优化查询计数
        return Ingredient.objects.select_related("category").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)

You can think of this as being something like your top-level urls.py file.

你可以把这看作是你的高层 urls.py 文件。

Testing everything so far 测试到目前为止的一切

We are going to do some configuration work, in order to have a working Django where we can test queries, before we move on, updating our schema.

我们将做一些配置工作,以便有一个可用的Django,在这里我们可以测试查询,然后继续更新我们的模式。

Update settings 更新设置

Next, install your app and GraphiQL in your Django project. GraphiQL is a web-based integrated development environment to assist in the writing and executing of GraphQL queries. It will provide us with a simple and easy way of testing our cookbook project.

接下来,在Django项目中安装应用程序和GraphiQL。GraphiQL是一个基于web的集成开发环境,用于帮助编写和执行GraphQL查询。它将为我们提供一个简单易行的方法来测试我们的食谱项目。

Add graphene_django to INSTALLED_APPS in cookbook/settings.py:

cookbook/settings.py内添加graphene_djangoINSTALLED_APPS 中:

# cookbook/settings.py

INSTALLED_APPS = [
    ...
    "graphene_django",
]

And then add the SCHEMA to the GRAPHENE config in cookbook/settings.py:

然后在cookbook/settings.py内将SCHEMA添加到GRAPHENE:

# cookbook/settings.py

GRAPHENE = {
    "SCHEMA": "cookbook.schema.schema"
}

Alternatively, we can specify the schema to be used in the urls definition, as explained below.

或者,我们可以指定在url定义中使用的模式,如下所述。

Creating GraphQL and GraphiQL views 创建GraphQL和GraphiQL视图

Unlike a RESTful API, there is only a single URL from which GraphQL is accessed. Requests to this URL are handled by Graphene’s GraphQLView view.

This view will serve as GraphQL endpoint. As we want to have the aforementioned GraphiQL we specify that on the parameters with graphiql=True.

与restfulapi不同,GraphQL只有一个URL可供访问。对这个URL的请求由Graphene的“GraphQLView”视图处理。

此视图将用作GraphQL端点。因为我们希望有上述的GraphiQL,所以我们在参数中指定“GraphiQL=True”。

# cookbook/urls.py

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

from graphene_django.views import GraphQLView

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

If we didn’t specify the target schema in the Django settings file as explained above, we can do so here using:

如果我们没有如上所述在Django设置文件中指定目标架构,我们可以在这里使用:

# cookbook/urls.py

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))),
]

Testing our GraphQL schema 测试GraphQL模式

We’re now ready to test the API we’ve built. Let’s fire up the server from the command line.

我们现在已经准备好测试我们构建的API了。让我们从命令行启动服务器。

python manage.py runserver

Performing system checks...
Django version 3.0.7, using settings 'cookbook.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Go to localhost:8000/graphql and type your first query!

转到localhost:8000/graphql并键入您的第一个查询!

query {
  allIngredients {
    id
    name
  }
}

If you are using the provided fixtures, you will see the following response:

如果您正在使用所提供的固件,您将看到以下响应:

{
  "data": {
    "allIngredients": [
      {
        "id": "1",
        "name": "Eggs"
      },
      {
        "id": "2",
        "name": "Milk"
      },
      {
        "id": "3",
        "name": "Beef"
      },
      {
        "id": "4",
        "name": "Chicken"
      }
    ]
  }
}

Congratulations, you have created a working GraphQL server 🥳!

祝贺您,您已经创建了一个正在工作的GraphQL服务器🥳!

Note: Graphene automatically camelcases all field names for better compatibility with JavaScript clients.

注:Graphene自动camelcase 所有字段名,以便更好地与JavaScript客户端兼容。

Getting relations 建立关系

Using the current schema we can query for relations too. This is where GraphQL becomes really powerful!

使用当前模式,我们也可以查询关系。这就是GraphQL变得非常强大的地方!

For example, we may want to get a specific categories and list all ingredients that are in that category.

例如,我们可能需要得到一个特定的类别,并列出该类别中的所有成分。

We can do that with the following query:

我们可以通过以下查询来实现:

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

This will give you (in case you are using the fixtures) the following result:

这将给您(如果您正在使用固定装置)以下结果:

{
  "data": {
    "categoryByName": {
      "id": "1",
      "name": "Dairy",
      "ingredients": [
        {
          "id": "1",
          "name": "Eggs"
        },
        {
          "id": "2",
          "name": "Milk"
        }
      ]
    }
  }
}

We can also list all ingredients and get information for the category they are in:

我们还可以列出所有成分并获取其所属类别的信息:

query {
  allIngredients {
    id
    name
    category {
      id
      name
    }
  }
}

Summary 摘要

As you can see, GraphQL is very powerful and integrating Django models allows you to get started with a working server quickly.

如您所见,GraphQL非常强大,集成Django模型可以让您快速开始使用一个正常工作的服务器。

If you want to put things like django-filter and automatic pagination in action, you should continue with the Relay tutorial.

如果您想使用django-filter和自动分页,您应该继续Relay tutorial

A good idea is to check the Graphene documentation so that you are familiar with it as well.

一个好主意是检查 Graphene 文档,以便您也熟悉它。

posted @ 2020-09-25 07:24  双葫  阅读(284)  评论(0编辑  收藏  举报