This README.md file provides instructions for setting up a Django project with GraphQL using the provided code snippets.
Before starting, ensure you have the following installed on your system:
- Python 3
- Pip (Python package manager)
-
Create a virtual environment:
python3 -m venv venv
-
Activate the virtual environment:
source venv/bin/activate
-
Install Django:
pip install django
-
Install GraphQL support using Graphene-Django:
pip install graphene-django
-
Create a new Django project and an app:
django-admin startproject core . python3 manage.py startapp books
-
Add the 'books' and 'graphene_django' app to
INSTALLED_APPS
incore/settings.py
:# core/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'graphene_django', # Add 'graphene_django' here 'books', # Add 'books' here ]
-
Define a model in
books/models.py
:# books/models.py from django.db import models class Book(models.Model): title = models.CharField(max_length=100) excerpt = models.TextField() def __str__(self): return self.title
-
Create database tables and apply migrations:
python3 manage.py makemigrations python3 manage.py migrate
-
Create a GraphQL schema file:
touch books/schema.py
-
Populate
books/schema.py
with GraphQL schema definitions:# books/schema.py import graphene from graphene_django import DjangoObjectType from .models import Book class BookType(DjangoObjectType): class Meta: model = Book fields = ("id", "title", "excerpt") class Query(graphene.ObjectType): allBooks = graphene.List(BookType) def resolve_allBooks(root, info): return Book.objects.all() schema = graphene.Schema(query=Query)
-
Update
core/urls.py
to include the Books endpoint:# core/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('books.urls')) ]
-
Update
books/urls.py
to include the GraphQL endpoint:# core/urls.py from django.urls import path from graphene_django.views import GraphQLView from books.schema import schema urlpatterns = [ # ... path("graphql", GraphQLView.as_view(graphiql=True, schema=schema)), ]
-
Register the
Book
model incore/admin.py
:# core/admin.py from django.contrib import admin from books.models import Book admin.site.register(Book)
-
Create a superuser for the admin interface:
python3 manage.py createsuperuser
-
Visit
http://localhost:8000/admin
in your browser and log in with the superuser credentials you created. -
Add few books from the admin interface:
-
Start the development server once more:
python3 manage.py runserver
-
Visit
http://localhost:8000/graphql
and play with queries
Now, you have set up a Django project with GraphQL support. You can use the GraphQL endpoint at http://localhost:8000/graphql
to interact with your data. The Book
model is available in the admin interface for data management.