Serializers की मूल बातें
In this page:
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.
# 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.
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.
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 करता है।
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.
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. #}
- Serializer के
Meta.fieldsमें एक field listing करना जो model पर मौजूद नहीं, जो एक runtime error का कारण बनता है। - यह भूल जाना कि ModelSerializer की default fields read-write होती हैं, इसलिए sensitive fields (जैसे कहीं और उपयोग होने वाली एक internal id) explicitly exclude न किए जाने पर unintentionally exposed हो सकती हैं।
- Incoming request data से बने serializer पर
is_valid()call करने से पहलेserializer.datacall करना, जो एकAssertionErrorraise करता है।
- एक serializer Django model instances को JSON में convert करता है (serialization) और incoming JSON को वापस Python data में validate करता है (deserialization)।
- ModelSerializer एक model के आधार पर automatically fields generate करता है, वैसे ही जैसे ModelForm form fields generate करता है।
Meta.fieldsexactly control करता है कि कौन सी model fields API के through expose होती हैं।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: