visit
You may also be interested in the
Store in models.py
from django.db import models
class Store(models.Model):
name = models.CharField(max_length=256, verbose_name='Store name')
address = models.CharField(max_length=256)
email = models.EmailField()
opening_hours = models.TimeField(verbose_name='Opening hours')
closing_hours = models.TimeField(verbose_name='Closing hours')
And Product in another models.py file:
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
class Product(models.Model):
title = models.CharField(max_length=256, verbose_name='Product title')
description = models.TextField(max_length=5000)
price = models.FloatField(
validators=[MinValueValidator(0.0), MaxValueValidator(10000.0)],
)
amount = models.SmallIntegerField()
store = models.ForeignKey('stores.Store', on_delete=models.CASCADE)
pip install graphene-django
In settings.py file:
INSTALLED_APPS = [
...
"django.contrib.staticfiles", # Required for GraphiQL
"graphene_django"
]
GRAPHENE = {
"SCHEMA": "app.schema.schema"
}
We need to add a graphql URL to the urls.py of your Django project:
from graphene_django.views import GraphQLView
from django.contrib import admin
from django.urls import path
from django.views.decorators.csrf import csrf_exempt
from app.schema import schema
urlpatterns = [
path('admin/', admin.site.urls),
path("graphql", csrf_exempt(GraphQLView.as_view(graphiql=True, schema=schema))),
]
import graphene
from graphene_django import DjangoObjectType
from app.stores.models import Store
from app.products.models import Product
class StoreType(DjangoObjectType):
class Meta:
model = Store
fields = (
'id', 'name', 'address', 'email', 'opening_hours', 'closing_hours',
)
class ProductType(DjangoObjectType):
class Meta:
model = Product
fields = (
'id', 'title', 'description', 'price', 'amount', 'store',
)
class Query(graphene.ObjectType):
stores = graphene.List(StoreType)
products = graphene.List(ProductType)
def resolve_stores(root, info, **kwargs):
# Querying a list
return Store.objects.all()
def resolve_products(root, info, **kwargs):
# Querying a list
return Product.objects.all()
schema = graphene.Schema(query=Query)
For testing you can just type //127.0.0.1:8000/graphql in your browser:
class StoreInput(graphene.InputObjectType):
name = graphene.String()
address = graphene.String()
email = graphene.String()
opening_hours = graphene.Time()
closing_hours = graphene.Time()
class CreateStore(graphene.Mutation):
class Arguments:
input = StoreInput(required=True)
store = graphene.Field(StoreType)
@classmethod
def mutate(cls, root, info, input):
store = Store()
store.name = input.name
store.address = input.address
store.email = input.email
store.opening_hours = input.opening_hours
store.closing_hours = input.closing_hours
store.save()
return CreateStore(store=store)
class UpdateStore(graphene.Mutation):
class Arguments:
input = StoreInput(required=True)
id = graphene.ID()
store = graphene.Field(StoreType)
@classmethod
def mutate(cls, root, info, input, id):
store = Store.objects.get(pk=id)
store.name = input.name
store.address = input.address
store.email = input.email
store.opening_hours = input.opening_hours
store.closing_hours = input.closing_hours
store.save()
return UpdateStore(store=store)
class ProductInput(graphene.InputObjectType):
title = graphene.String()
description = graphene.String()
price = graphene.Float()
amount = graphene.Int()
store = graphene.ID()
class CreateProduct(graphene.Mutation):
class Arguments:
input = ProductInput(required=True)
product = graphene.Field(ProductType)
@classmethod
def mutate(cls, root, info, input):
product = Product()
product.title = input.title
product.description = input.description
product.price = input.price
product.amount = input.amount
product.store = input.store
product.save()
return CreateProduct(product=product)
class UpdateProduct(graphene.Mutation):
class Arguments:
input = ProductInput(required=True)
id = graphene.ID()
product = graphene.Field(ProductType)
@classmethod
def mutate(cls, root, info, input, id):
product = Product.objects.get(pk=id)
product.title = input.title
product.description = input.description
product.price = input.price
product.amount = input.amount
product.store = input.store
product.save()
return UpdateProduct(product=product)
class Mutation(graphene.ObjectType):
create_store = CreateStore.Field()
update_store = UpdateStore.Field()
update_product = CreateProduct.Field()
create_product = UpdateProduct.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
pip install djangorestframework
In settings.py file:
INSTALLED_APPS = [
...
'rest_framework',
]
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
You should make serializers in products/serializers.py:
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
And also, in stores/serializers.py:
from rest_framework import serializers
from .models import Store
class StoreSerializer(serializers.ModelSerializer):
class Meta:
model = Store
fields = '__all__'
from rest_framework import generics
from rest_framework.permissions import AllowAny
from .serializers import ProductSerializer
from .models import Product
class RetriveUpdateDestroyProductView(generics.RetrieveUpdateDestroyAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
permission_classes = [AllowAny]
class ListCreateProductView(generics.ListCreateAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
permission_classes = [AllowAny]
from rest_framework import generics
from rest_framework.permissions import AllowAny
from .serializers import StoreSerializer
from .models import Store
class RetriveUpdateDestroyStoreView(generics.RetrieveUpdateDestroyAPIView):
queryset = Store.objects.all()
serializer_class = StoreSerializer
permission_classes = [AllowAny]
class ListCreateStoreView(generics.ListCreateAPIView):
queryset = Store.objects.all()
serializer_class = StoreSerializer
permission_classes = [AllowAny]
And connect it in urls.py file:
In app/stores/urls.py
from django.urls import path
from .views import ListCreateStoreView, RetriveUpdateDestroyStoreView
urlpatterns = [
path('<int:pk>/', RetriveUpdateDestroyStoreView.as_view(), name='store-get-update-delete'),
path('', ListCreateStoreView.as_view(), name='store-post-list'),
]
In app/products/urls.py
from django.urls import path
from .views import ListCreateProductView, RetriveUpdateDestroyProductView
urlpatterns = [
path('<int:pk>/', RetriveUpdateDestroyProductView.as_view(), name='product-get-update-delete'),
path('', ListCreateProductView.as_view(), name='product-post-list'),
]
And in app/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('store/', include('app.stores.urls')),
path('product/', include('app.products.urls')),
]