E-Commerce GraphQL API with Django | Python

Setup The Project

mkdir ecommerce_graphql
cd ecommerce_graphql
pipenv shell
pipenv install django
django-admin startproject core .
ecommerce_graphql
├── core
│ ├── asgi.py
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
├── Pipfile
└── Pipfile.lock

Plan The Database Tables Visually

Code The Models In Django Project

python manage.py startapp products
# core/settings.py
....
INSTALLED_APPS = [
....
'products',
]
# products/models.pyfrom django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=50)
class SubCategory(models.Model):
name = models.CharField(max_length=50)
category = models.ForeignKey(Category,
related_name='subCategories',
on_delete=models.CASCADE)
class Product(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category,
related_name='products',
on_delete=models.CASCADE)
subCategory = models.ForeignKey(SubCategory,
related_name='products',
on_delete=models.CASCADE)
description = models.TextField()
price = models.PositiveIntegerField()
amount_in_stock = models.PositiveIntegerField()
class ProductImage(models.Model):
product = models.ForeignKey(Product,
related_name='images',
on_delete=models.CASCADE)
image = models.ImageField(upload_to='productImages/')
class Rating(models.Model):
product = models.ForeignKey(Product,
related_name='ratings',
on_delete=models.CASCADE)
stars = models.PositiveIntegerField()
note = models.TextField()
rating_from = models.ForeignKey(User,
related_name='ratings_given',
on_delete=models.CASCADE)
created_on = models.DateTimeField(auto_now_add=True)
class Comment(models.Model):
product = models.ForeignKey(Product,
related_name='comments',
on_delete=models.CASCADE)
comment_from = models.ForeignKey(User,
related_name='comments_given',
on_delete=models.CASCADE)
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
pipenv install pillow
python manage.py makemigrations
python manage.py migrate
# core/settings.py MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media/'
# core/urls.py...
from django.conf import settings #new
from django.conf.urls.static import static #new
urlpatterns = [
....
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
python manage.py startapp orders
python manage.py startapp carts
# core/settings.py
....
INSTALLED_APPS = [
....
'products',
'orders', #new
'carts', #new
]
# orders/models.pyfrom django.db import modelsfrom products.models import Product
from django.contrib.auth.models import User
STATUS_CHOICES = [
('created', 'Created'),
('processing', 'Processing'),
('cancelled', 'Cancelled'),
('delivered', 'Delivered'),
]
class Order(models.Model):
product = models.ForeignKey(Product,
related_name='orders',
on_delete=models.CASCADE)
order_from = models.ForeignKey(User,
related_name='orders_given',
on_delete=models.CASCADE)
status = models.CharField(max_length=20,
default="created",
choices=STATUS_CHOICES)
created_on = models.DateTimeField(auto_now_add=True)
# carts/models.pyfrom django.db import modelsfrom products.models import Product 
from django.contrib.auth.models import User
class Cart(models.Model):
account = models.OneToOneField(User,
related_name='cart',
on_delete=models.CASCADE)
class CartItem(models.Model):
cart = models.ForeignKey(Cart,
related_name='items',
on_delete=models.CASCADE)
product = models.ManyToManyField(Product,
related_name='product')
amount = models.PositiveIntegerField(default=1)
python manage.py makemigrations
python manage.py migrage

Add New Models to Admin Panel

# products/admin.pyfrom django.contrib import adminfrom .models import (
Category,
SubCategory,
Product,
ProductImage,
Rating,
Comment,
)
admin.site.register(Category)
admin.site.register(SubCategory)
admin.site.register(Product)
admin.site.register(ProductImage)
admin.site.register(Rating)
admin.site.register(Comment)
# orders/admin.pyfrom django.contrib import adminfrom .models import Orderadmin.site.register(Order)
# carts/admin.pyfrom django.contrib import adminfrom .models import Cart, CartItemadmin.site.register(Cart)
admin.site.register(CartItem)
python manage.py createsuperuser

Query The Data with GraphQL

pipenv install graphene-django
# settings.py
...
INSTALLED_APPS = [
...
'graphene_django', # new
]
# core/urls.py
...
from graphene_django.views import GraphQLView #new
urlpatterns = [
...
path("graphql/", GraphQLView.as_view(graphiql=True)), #new
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# products/schema.pyimport graphene 
from graphene_django import DjangoObjectType
from .models import (
Category,
SubCategory,
Product,
ProductImage,
Rating,
Comment,
)
class ProductType(DjangoObjectType):
class Meta:
model = Product
class Query(graphene.ObjectType):
all_products = graphene.List(ProductType)
def resolve_all_products(root, info):
return Product.objects.all()
# core/schema.pyimport grapheneimport products.schemaclass Query(products.schema.Query, graphene.ObjectType):
pass
schema = graphene.Schema(query=Query)
# settings.py 
...
GRAPHENE = {
"SCHEMA": "core.schema.schema"
}

NOTE

--

--

--

Increasing my knowledge by sharing it.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How Gratify manages user conversations

fTokens | Ponzinomics & Pumpamentals In Depth

5C Core Part 2 — PDU Session and QoS

Python for Cybersecurity — Lesson 1: Introduction to Python

Good to know Azure DevOps Build Triggers

Adding colorbar and images to GIF animations created from Earth Engine

What does an Agile (DevOps) coach do, and how do you become a good Agile coach?

Why you should learn Apache Kafka

Logo of Apache Kafka

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Akhter

Akhter

Increasing my knowledge by sharing it.

More from Medium

Create a custom User model in Django 4.0

How to create alphabetical pagination with Django?

All about Views in Django REST Framework(DRF) — APIView

Setup WebSockets on a Django project