Home / Blogs

How to Integrate GraphQL in Django [2024]

Django
·

January 30, 2024

how-to-integrate-graphql-in-django

In the dynamic realm of web development, where efficiency and flexibility are paramount, Django has long been a stalwart framework, streamlining the creation of robust web applications. However, as our digital landscapes evolve, so too must our tools. Enter GraphQL, a game-changing query language for APIs, and Django, the seasoned web framework. Together, they form a symbiotic relationship, offering developers a paradigm shift in how data is queried and delivered.

This blog delves into the synergy between Django and GraphQL, exploring the marriage of a battle-tested framework with a cutting-edge query language.

We embark on a journey through the core concepts, integration strategies, and the myriad possibilities that unfold when Django embraces GraphQL. Whether you’re a Django aficionado or a GraphQL enthusiast, this exploration promises to unveil the potential for streamlined, flexible, and efficient data interactions within your Django projects.

To read more about integrating Django with React, refer to our blog How to Integrate Django With React in 2024

Step-by-Step Guide to Creating a Django Project with GraphQL:

Create Django Project:

Use django-admin to start a new project.

django-admin startproject djangographql

Install Required Packages.

Install graphql package using the following code:

pip install django graphene-django

Create a Django App:

Generate a new app within your project:

python manage.py startapp contact

Configure App in Settings.

Include the newly created app in the INSTALLED_APPS section of settings.py:

INSTALLED_APPS = [
    # ... other apps
    “contact”,
    “graphene_django”

]

Define Models and Schema in the App.

Link App URLs to Project.

Update djangographql/urls.py to include the app’s URLs.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path(‘contact/',include("contact.urls")),
   
]

Run Migrations:

Apply migrations to create database tables.

python manage.py makemigrations
python manage.py migrate

Create Django Models :

Now create new models in contact.models.py.

from django.db import models

   
class User(models.Model):
    username = models.CharField(max_length =100)
    password = models.CharField(max_length =100)

Create schemas:

GraphQL schemas in Django define data structures, queries, and mutations, allowing precise definitions of API capabilities. Within Django, these schemas guide data retrieval and manipulation, offering a clear contract between the client and server. Schemas enable seamless documentation, validation, and introspection, empowering developers to efficiently query, evolve, and secure their APIs. Integrating seamlessly with Django models, GraphQL schemas in Django facilitate a modern, flexible, and streamlined approach to data interaction, fostering enhanced development experiences and efficient communication between applications.

import graphene
from graphene_django.types import DjangoObjectType
from .models import Departmant, User

class UserType(DjangoObjectType):  # Use DjangoObjectType for better integration with Django models
    class Meta:
        model = User

class Query(graphene.ObjectType):
    all_users = graphene.List(UserType)


    def resolve_all_users(self, info, **kwargs):
        return User.objects.all()
schema = graphene.Schema(query=Query)

Connect schemas through URLs:

from django.urls import path, include
from graphene_django.views import GraphQLView
from .schema import schema
urlpatterns = [
    # ... other paths
    path('graphql/', GraphQLView.as_view(graphiql=True,schema=schema)),
]

Access the http://localhost:8000/graph/graphql/ to use graphql api. The query for searching all user objects is””” query { allUsers { id username password } } “””.

Also, we can follow the request body to fetch data.

{
 "query": "query { allUsers { id username password } }"
}

If your Django model includes a ForeignKey relationship, and you want to expose that relationship in your GraphQL schema, you can define a GraphQL type for the related model and include it in your UserType. Let’s say you have a model structure like this:

# models.py

from django.db import models

class Departmant(models.Model):
    name = models.CharField(max_length =100)
    students = models.IntegerField()
   
class User(models.Model):
    username = models.CharField(max_length =100)
    password = models.CharField(max_length =100)
    department_id = models.ForeignKey(Departmant,on_delete=models.CASCADE)

Now, you can update your GraphQL schema to include the related Department information for each User.

# schema.py

import graphene
from graphene_django.types import DjangoObjectType
from .models import User, Department

class DepartmentType(DjangoObjectType):
    class Meta:
        model = Department

class UserType(DjangoObjectType):
    class Meta:
        model = User

    # Include the ForeignKey relationship


class Query(graphene.ObjectType):
    all_users = graphene.List(UserType)
    department = graphene.Field(DepartmentType)

    def resolve_all_users(self, info, **kwargs):
        return User.objects.all()

schema = graphene.Schema(query=Query)

In this updated schema: Added a DepartmentType to represent the Department model. In the UserType, include a department field of type DepartmentType. This field corresponds to the ForeignKey relationship in the User model. In the resolve_all_users method, retrieve all users, and each user object will include the related department information. Now, when you query for allUsers, you can also request information about the related department:

query {
  allUsers {
    id
    username
    departmentId {
      id
      name
    }
  }
}

This query will return a list of users, and for each user, it will include the associated department information. Adjust the field names based on your actual model structure.

To read more about building a real-time notification system with Django-notifications-hq, refer to our blog How to Build a Real-Time Notification System With Django-notifications-hq

Conclusion

In conclusion, the marriage of Django and GraphQL heralds a transformative era in web development. Django’s robust framework, coupled with GraphQL’s flexible querying, orchestrates an exquisite symphony of efficiency and clarity. Together, they redefine how data is modeled, queried, and evolved, offering developers unparalleled control and precision. The seamless integration of GraphQL schemas into Django projects elevates not just the development experience but also the efficiency and scalability of applications. This dynamic duo not only empowers developers to craft sophisticated APIs but also paves the way for resilient, adaptable, and forward-looking web solutions in the ever-evolving landscape of digital innovation.

Horilla Editorial Team Author

Horilla Editorial Team is a group of experienced writers and editors who are passionate about HR software. We have a deep understanding of the HR landscape and are committed to providing our readers with the most up-to-date and informative content. We have written extensively on a variety of HR software topics, including applicant tracking systems, performance management software, and payroll software etc. We are always looking for new ways to share our knowledge with the HR community. If you have a question about HR software, please don't hesitate to contact us.