Notice
Recent Posts
Recent Comments
Link
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

최용우

Django-graphene에서 타입 이름 변경하기 본문

장고

Django-graphene에서 타입 이름 변경하기

용우쨩 2024. 10. 27. 10:21

장고에서 GraphQL을 사용하기 위해선 타입을 지정해야한다.

여기서 말하는 타입이란 데이터베이스의 테이블 명세서 같은 개념이다.

즉, 스키마를 지정하고 이것을 GraphQL에게 알려주어야 한다.

 

아래 코드 예제를 보자.

 

1. types.py

#myapp/types.py
from graphene_django import DjangoObjectType

class MyType(DjangoObjectType):
    class Meta:
        model = MyType
        name = 'My_Name_Hello' #내가 지정하고 싶은 타입 이름

 

2. queries.py

#myapp/queries.py
import graphene

mytypes = graphene.Field(MyType)
    @login_required
    def resolve_mytypes(self, info):
        try:
            return MyType.object.all()
        except Exception as e:
            raise e

 

3.schema.py

#myproject/schema.py
import graphene
from myapp.queries import Query as MyQuery

class Query(MyQuery, graphene.ObjectType):
    pass

 

4.urls.py

#config/urls.py
from django.urls import path
from graphene_django.views import GraphQLView

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

 

단 몇줄의 코드로 GraphQL API를 완성하였다.

타입의 메타클래스에서 이름을 바꾸는 것으로 손쉽게 원하는 타입 이름을 지정할 수 있다.