← Back to Django Course | Chapter 14: REST API with DRF | Lesson 3 of 6

Serializers की मूल बातें

एक serializer एक translator है जो एक Django model को JSON में बदलता है, और incoming JSON को वापस एक model में बदलता है।
Syntax
markup
from rest_framework import serializers

class ModelNameSerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelName
        fields = ['field1', 'field2']

Serializers की ज़रूरत क्यों है

Book objects की एक QuerySet सीधे HTTP पर send नहीं हो सकती — इसे पहले JSON text बनना होता है। एक serializer exactly define करता है कि हर model field एक JSON field में कैसे map हो, और वापस आ रहे data को validate करता है।

उदाहरण: Why Serializers Are Needed

A QuerySet of Book objects can't be sent over HTTP directly — it needs to become JSON text first. A serializer defines exactly how each model field maps to a JSON field, and validates data coming back in.

markup
# Python object (a Book instance) --> serializer --> JSON text
# {'id': 1, 'title': 'Dune', 'author': 'Frank Herbert', 'published_year': 1965}
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

एक ModelSerializer बनाना

ModelSerializer DRF का ModelForm equivalent है: यह एक model inspect करता है और आपकी listed fields के आधार पर matching serializer fields अपने आप बनाता है।

उदाहरण: Creating a ModelSerializer

ModelSerializer is the DRF equivalent of ModelForm: it inspects a model and builds matching serializer fields automatically, based on the fields you list.

markup
from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_year']
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

एक Queryset को Serialize करना

कई objects को एक साथ serialize करने के लिए many=True के साथ एक queryset pass करें, फिर JSON response के लिए ready plain Python data पाने के लिए .data access करें।

उदाहरण: Serializing a Queryset

Pass a queryset with many=True to serialize multiple objects at once, then access .data to get plain Python data ready for a JSON response.

bash
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
print(serializer.data)
# [OrderedDict([('id', 1), ('title', 'Dune'), ('author', 'Frank Herbert'), ('published_year', 1965)])]

⚠️ Run this in your own terminal or Node.js environment.

Incoming Data को Validate करना

Raw input data से एक serializer बनाते समय, .data या .validated_data पढ़ने से पहले is_valid() call करें — यह एक ModelForm की तरह field-level validation run करता है।

Warning: is_valid() call करने से पहले serializer.data पढ़ना एक error raise करता है, क्योंकि DRF को अभी तक नहीं पता कि data valid है या नहीं।

उदाहरण: Validating Incoming Data

When building a serializer from raw input data, call is_valid() before reading .data or .validated_data — this runs field-level validation like a ModelForm does.

markup
serializer = BookSerializer(data={'title': 'Dune', 'author': 'Frank Herbert', 'published_year': 1965})
if serializer.is_valid():
    book = serializer.save()
else:
    print(serializer.errors)
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Serializer के Meta.fields में एक field listing करना जो model पर मौजूद नहीं, जो एक runtime error का कारण बनता है।
  2. यह भूल जाना कि ModelSerializer की default fields read-write होती हैं, इसलिए sensitive fields (जैसे कहीं और उपयोग होने वाली एक internal id) explicitly exclude न किए जाने पर unintentionally exposed हो सकती हैं।
  3. Incoming request data से बने serializer पर is_valid() call करने से पहले serializer.data call करना, जो एक AssertionError raise करता है।
चैप्टर सारांश
  • एक serializer Django model instances को JSON में convert करता है (serialization) और incoming JSON को वापस Python data में validate करता है (deserialization)।
  • ModelSerializer एक model के आधार पर automatically fields generate करता है, वैसे ही जैसे ModelForm form fields generate करता है।
  • Meta.fields exactly control करता है कि कौन सी model fields API के through expose होती हैं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.