MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
CRUD, Authentication, Filtering, Pagination0%
Study Materials
REST API Development with DjangoProgress 0%
1.1REST Principles1.2HTTP Methods Overview1.3Status Codes
10.1Build REST API for E-commerce App10.2CRUD, Authentication, Filtering, Pagination10.3Test & Document API
HomeTutorialsREST API Development with DjangoCRUD, Authentication, Filtering, Pagination
Test & Document API

CRUD, Authentication, Filtering, Pagination

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

DRF Capstone: Orders, Cart Checkout, and JWT Workflows

Building on our data models, we now implement the business logic: cart serializers, dynamic calculations, checkout transactions with atomic inventory decrements, and secure JWT authentication.


1. Serializers for Products, Carts, and Items

In store/serializers.py:

1from rest_framework import serializers
2from decimal import Decimal
3from store.models import Category, Product, Cart, CartItem, Order, OrderItem
4 
5class ProductSerializer(serializers.ModelSerializer):
6 price_with_tax = serializers.SerializerMethodField()
7 
8 class Meta:
9 model = Product
10 fields = ['id', 'title', 'slug', 'description', 'price', 'price_with_tax', 'inventory', 'category']
11 
12 def get_price_with_tax(self, product):
13 return round(product.price * Decimal(1.10), 2)
14 
15class CartItemSerializer(serializers.ModelSerializer):
16 total_price = serializers.SerializerMethodField()
17 product = ProductSerializer(read_only=True)
18 
19 class Meta:
20 model = CartItem
21 fields = ['id', 'product', 'quantity', 'total_price']
22 
23 def get_total_price(self, cart_item):
24 return cart_item.quantity * cart_item.product.price
25 
26class AddCartItemSerializer(serializers.ModelSerializer):
27 product_id = serializers.IntegerField()
28 
29 class Meta:
30 model = CartItem
31 fields = ['id', 'product_id', 'quantity']
32 
33 def validate_product_id(self, value):
34 if not Product.objects.filter(pk=value).exists():
35 raise serializers.ValidationError("No product found with given ID.")
36 return value
37 
38 def save(self, **kwargs):
39 cart_id = self.context['cart_id']
40 product_id = self.validated_data['product_id']
41 quantity = self.validated_data['quantity']
42 
43 try:
44 cart_item = CartItem.objects.get(cart_id=cart_id, product_id=product_id)
45 cart_item.quantity += quantity
46 cart_item.save()
47 self.instance = cart_item
48 except CartItem.DoesNotExist:
49 self.instance = CartItem.objects.create(cart_id=cart_id, **self.validated_data)
50 return self.instance

2. Atomic Checkout with transaction.atomic

When converting a cart to an order:

  1. 1
    Verify cart is not empty.
  2. 2
    Check inventory availability.
  3. 3
    Decrement product stock.
  4. 4
    Create order & order items.
  5. 5
    Delete the cart.
1from django.db import transaction
2from rest_framework.exceptions import ValidationError
3 
4class CreateOrderSerializer(serializers.Serializer):
5 cart_id = serializers.UUIDField()
6 shipping_address = serializers.CharField(max_length=255)
7 
8 def validate_cart_id(self, cart_id):
9 if not Cart.objects.filter(pk=cart_id).exists():
10 raise ValidationError("Invalid cart ID.")
11 if CartItem.objects.filter(cart_id=cart_id).count() == 0:
12 raise ValidationError("The shopping cart is empty.")
13 return cart_id
14 
15 def save(self, **kwargs):
16 with transaction.atomic():
17 cart_id = self.validated_data['cart_id']
18 user = self.context['user']
19 shipping_address = self.validated_data['shipping_address']
20 
21 # Create Order
22 order = Order.objects.create(
23 customer=user,
24 shipping_address=shipping_address
25 )
26 
27 cart_items = CartItem.objects.select_related('product').filter(cart_id=cart_id)
28 order_items = []
29 
30 for item in cart_items:
31 product = item.product
32 if product.inventory < item.quantity:
33 raise ValidationError(f"Insufficient stock for {product.title}. Available: {product.inventory}")
34
35 # Deduct inventory
36 product.inventory -= item.quantity
37 product.save()
38 
39 order_items.append(
40 OrderItem(
41 order=order,
42 product=product,
43 unit_price=product.price,
44 quantity=item.quantity
45 )
46 )
47 
48 OrderItem.objects.bulk_create(order_items)
49 # Flush cart
50 Cart.objects.filter(pk=cart_id).delete()
51 
52 return order

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why is transaction.atomic() indispensable during the order creation workflow?
Question 2
Why is OrderItem.objects.bulk_create(order_items) preferred over calling .save() in a loop?
Question 3
What happens in AddCartItemSerializer.save() if a customer adds a product that already exists in their cart?
Question 4
Why is select_related('product') used when querying CartItem.objects.filter(cart_id=cart_id)?
Question 5
Where should user = self.context['user'] be supplied to the serializer?
Next Lesson

Test & Document API

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Build REST API for E-commerce AppTest & Document API

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master REST API Development with Django with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext