フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

Django/GrapheneでGraphQL実装②

はじめに

  • 前回、Django/GrapheneでGraphQLの実装を途中まで行い、エラーが発生した箇所で終ったので、その続きから調査を行う px-wing.hatenablog.com

  • 前回のエラーはモデルを作成していないことによるエラーのようだったので、モデルを作成してみる

想定するテーブル

f:id:PX-WING:20200803082427p:plain

モデルの作成

  • アプリケーション側のmodels.pyファイルに下記のようにモデルを作成する
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 Article(models.Model):
    title = models.CharField(max_length=255)
    notes = models.TextField()
    category = models.ForeignKey(
        Category, related_name='articles', on_delete=models.CASCADE)

    def __str__(self):
        return self.title

Migrate

# python manage.py makemigrations
Migrations for 'boardapp':
  boardapp/migrations/0001_initial.py
    - Create model Category
    - Create model Article

# python manage.py migrate 
Operations to perform:
  Apply all migrations: admin, auth, boardapp, contenttypes, sessions
Running migrations:
  Applying boardapp.0001_initial... OK

プロジェクトのschema.pyを変更

import graphene

import boardapp.schema


class Query(boardapp.schema.Query, graphene.ObjectType):
    # This class will inherit from multiple Queries
    # as we begin to add more apps to our project
    pass

schema = graphene.Schema(query=Query)

アプリケーションのschema.pyを変更

import graphene

from graphene_django.types import DjangoObjectType

from .models import Category, Article


class CategoryType(DjangoObjectType):
    class Meta:
        model = Category


class ArticleType(DjangoObjectType):
    class Meta:
        model = Article

class Query(object):
    all_categories = graphene.List(CategoryType)
    all_articles = graphene.List(ArticleType)

    def resolve_all_categories(self, info, **kwargs):
        return Category.objects.all()

    def resolve_all_articles(self, info, **kwargs):
        # We can easily optimize query count in the resolve method
        return Article.objects.select_related('category').all()

テストデータを管理画面から作成する

f:id:PX-WING:20200804081316p:plain

GraphQLの実行

f:id:PX-WING:20200804081202p:plain

エラーの原因

  • Django/GrapheneでGraphQL実装①のエラーの原因はschema.pyの記述が一部間違っていたので修正したところ解決できた