Django restframework API Blog #2

Salom hammaga. O'tgan safar darsda kategoriyalar listini ko'rsatgan edim. Bugungi darsda qanday qilib api orqali category yaratish va o'zgartirish va o'chirishni o'rgataman. Ya'ni, dasturlashda CRUD deyiladi(video maqolaning eng quyi qismida).

views.py ga kiramiz

0 #rest_frameworkdan kutubxonani import qilib olamiz

1 #CreateAPIView - buning vazifani - category yaratish;

2 # RetrieveUpdateAPIView - buning vazifasi - category o'zgartirish;

3 #DestroyAPIView - buning vazifasi category - o'chirish;

4 #ListAPIView - buning vazifasi ma'umotlar omboridagi ma'lumotlarni ko'rsatish, ya'ni chiqarish.

views.py

from django.shortcuts import render
from .serilazers import CategoryListAPIView
from rest_framework.generics import ListAPIView,CreateAPIView,RetrieveUpdateAPIView,DestroyAPIView
from app.models import Category
# Create your views here.
class CategoryList(ListAPIView):
    queryset = Category.objects.all()
    serializer_class = CategoryListAPIView
class CreateCategory(CreateAPIView):
    queryset = Category.objects.all()
    serializer_class = CategoryListAPIView #serilizatsiya o'sha-o'sha qoladi
class CategoryUpdate(RetrieveUpdateAPIView):
    queryset = Category.objects.all()
    serializer_class = CategoryListAPIView #serilizatsiya o'sha-o'sha qoladi
#endi o'chiramiz
class CategoryDelete(DestroyAPIView):
    queryset = Category.objects.all()
    serializer_class = CategoryListAPIView #serilizatsiya o'sha-o'sha qoladi

ana endi urls.py ga kirib, havolani to'g'rilab qo'yamiz:

from django.urls import path
from .views import CategoryList,CreateCategory,CategoryUpdate,CategoryDelete
#bu urlga so'rov kelganda http://127.0.0.1:8000/api/list categorylist klass ishlaydi
urlpatterns = [
    path('list',CategoryList.as_view()),
    path('create',CreateCategory.as_view()),
    path('update/<int:pk>',CategoryUpdate.as_view()) ,#<int:pk /1 yoki /2 bu degani 2 yoki 1 category o'zgartirish
    path('delete/<int:pk>',CategoryDelete.as_view())
]
#mana o'chirish ham bo'ldi. Endi shuni postmandan tekshirib ko'ramiz

Ana endi postmanda ham tekshirib ko'rsak bo'ladi:

Hamma categorylar

Category qo'shish

Categoryni o'zgartirish


Categoryni o'chirish


Mover:


YouTube:

Ushbu dars kodini github'dan yuklab olishingiz mumkin.

Bugungi dars tugadi. O'ylaymanki, sizlarga dars yoqdi. Savolaringiz yoki qo'shimcha fikringiz bo'lsa, izohda qoldiring.


begyypy

Muallif haqida

Sadullayev Bekhzod Boxodirvich Python Django Backend Developer


Blogdagi so‘nggi maqolalar:


Birinchi bo‘ling!

Iltimos, fikr bildirish uchun saytga kiring yoki ro‘yxatdan o‘ting!