CONFIGURATIONS mkdir your_project_name python -m venv venv venv/Scripts/activate pip install django or django-admin startproject core . py manage.py startapp books
MIGRATIONS py manage.py makemigrations py manage.py migrate py manage.py runserver
COLLABORATION *pip freeze > requirements.txt *pip install -r requirements.txt
OTHER INSTALLATIONS pip install graphene-django
*Create model called Books, create schema.py both inside books module class Books(models.Model): title = models.CharField(max_length=100) excerpt = models.TextField()
def __str__(self):
return self.title
- add path('books/', include('books.urls')), in project's url.py and add url code from graphene documantation to your books urls.py.. polymoph them ... :return Books.objects.all()
i.e from books.schema import schema , path('graphql/', GraphQLView.as_view(graphiql=True, schema=schema)), and in admin add from .models import Books , admin.site.register(Books)
import graphene from graphene_django import DjangoObjectType from .models import Books
class BooksType(DjangoObjectType): class Meta: model = Books fields = ("id", "title", "excerpt")
class CreateBooks(graphene.Mutation): class Arguments: title = graphene.String() excerpt = graphene.String()
ok = graphene.Boolean()
book = graphene.Field(BooksType)
def mutate(self, info, title, excerpt):
book = Books(title=title, excerpt=excerpt)
book.save()
return CreateBooks(ok=True, book=book)
class DeleteBooks(graphene.Mutation): class Arguments: id = graphene.Int()
ok = graphene.Boolean()
def mutate(self, info, id): book = Books.objects.get(id=id) book.delete() return DeleteBooks(ok=True) class UpdateBooks(graphene.Mutation): class Arguments: id = graphene.Int() title = graphene.String() excerpt = graphene.String()
ok = graphene.Boolean() book = graphene.Field(BooksType)
def mutate(self, info, id, title, excerpt): book = Books.objects.get(id=id) book.title = title book.excerpt = excerpt book.save() return UpdateBooks(ok=True, book=book)
class Mutation(graphene.ObjectType): createBook = CreateBooks.Field() deleteBook = DeleteBooks.Field() updateBook = UpdateBooks.Field()
class Query(graphene.ObjectType): books = graphene.List(BooksType)
def resolve_books(root, info):
return Books.objects.all()
# return Books.objects.filter(title="django")
schema = graphene.Schema(query=Query, mutation=Mutation)
-
Query query{ books{ id title excerpt } }
-
Mutation Add mutation { createBook(title: "Crena Zveda", excerpt: "Lekki GARDENS") { ok book { id title excerpt } } }
-
Mutation Delete mutation { deleteBook(id: 1) { ok } }
-
Mutation Updatemutation { updateBook(id: 2, title: "Kada Plaza Ltd", excerpt: "Lekki Gardens") { ok book { id title excerpt } } }