Django Cheat Sheet (codeinsightacademy.com)
pip3 install djangorestframework
python3 manage.py startapp employee
Note: Make sure your sql service is running.
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webpage',
'rest_framework',
'employee',
]
employee/models.py
from django.db import models
class Employee(models.Model):
post = models.CharField(max_length = 100)
name = models.CharField(max_length = 100)
salary = models.IntegerField()
is_active = models.BooleanField(default=False)
added_date = models.DateField(auto_created=True)
updated_date = models.DateField(auto_now=True)
def __str___(self):
return self.title
to make and apply the migrations run
./manage.py makemigrations
./manage.py migrate
employee/serializers.py
from rest_framework import serializers
from employee.models import Employee
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = "__all__"
employee/views.py
from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.generics import CreateAPIView
from rest_framework.generics import DestroyAPIView
from rest_framework.generics import UpdateAPIView
from employee.serializers import EmployeeSerializer
from employee.models import Employee
class ListEmpAPIView(ListAPIView):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer
class CreateEmpAPIView(CreateAPIView):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer
class UpdateEmpAPIView(UpdateAPIView):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer
class DeleteEmpAPIView(DestroyAPIView):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer
employee/urls.py
from django.urls import path
from employee import views
urlpatterns = [
path("",views.ListEmpAPIView.as_view(),name="employee_list"),
path("create/", views.CreateEmpAPIView.as_view(),name="employee_create"),
path("update/<int:pk>/",views.UpdateEmpAPIView.as_view(),name="update_employee"),
path("delete/<int:pk>/",views.DeleteEmpAPIView.as_view(),name="delete_employee")
]
main urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/employee/',include("employee.urls"))
]
Run the api in postman with urls
POST request : http://localhost:8000/api/v1/employee/create/
GET request : http://localhost:8000/api/v1/employee
UPDATE request : http://localhost:8000/api/v1/employee/update/1/
DELETE request : http://localhost:8000/api/v1/employee/delete/1/