Django Essentials

Django REST Framework_004: erializers and Model-to-JSON Conversion

codeaddict 2025. 2. 6. 23:51

In this lesson, we will dive deeper into Django REST Framework (DRF) serializers, which are a crucial component for converting complex data types, such as Django models, into Python data types that can be easily rendered into JSON, XML, or other content types. We will also explore the important methods and concepts related to serializers, and how they fit into the broader context of building RESTful APIs with Django.


What is a Serializer?

A serializer in Django REST Framework is a component that allows you to convert complex data types (like Django models) into Python data types that can be easily rendered into JSON, XML, or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types after validating the incoming data.

In simpler terms, serializers help you:

  1. Convert Django models to JSON: When you want to send data from your Django application to a client (e.g., a web browser or mobile app), serializers convert your Django model instances into JSON format.
  2. Convert JSON to Django models: When you receive data from a client (e.g., a form submission), serializers validate the data and convert it back into a Django model instance.

 


Step 1: Setting Up Your Django Project

Before we dive into serializers, let’s ensure that your Django project is set up correctly.

  1. Install Django and Django REST Framework:
pip install django djangorestframework

2. Create a Django Project:

django-admin startproject myproject cd myproject

3. Create a Django App:

python manage.py startapp myapp

4. Add rest_framework and myapp to INSTALLED_APPS:
In myproject/settings.py, add:

INSTALLED_APPS = [ … 'rest_framework', 'myapp', ]

Step 2: Creating a Model

Let’s create a simple Book model in myapp/models.py:

from django.db import models
class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    published_date = models.DateField()
    isbn = models.CharField(max_length=13, unique=True)
    def __str__(self):
        return self.title

5. Run Migrations:

python manage.py makemigrations 
python manage.py migrate

Step 3: Creating a Serializer

Serializers are defined in a serializers.py file within your app. Let's create a serializer for the Book model.

In myapp/serializers.py, create a BookSerializer:

from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_date', 'isbn']

Key Points About Serializers:

  • ModelSerializer: This is a shortcut for creating serializers that map closely to Django models. It automatically generates fields based on the model and provides default implementations for creating and updating instances.
  • fields: This attribute specifies which fields from the model should be included in the serialized output. You can also use __all__ to include all fields.
  • read_only_fields: You can specify fields that should be read-only (e.g., id).
  • extra_kwargs: This allows you to specify additional options for fields, such as making a field write-only or adding validation rules.

Step 4: Creating Views

Now that we have a serializer, let’s create views to handle API requests. We’ll use DRF’s generic views to simplify the process.

In myapp/views.py:

from rest_framework import generics
from .models import Book
from .serializers import BookSerializer

class BookListCreateView(generics.ListCreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
class BookDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

Key Points About Views:

  • ListCreateAPIView: This view handles both listing all instances of a model and creating new instances.
  • RetrieveUpdateDestroyAPIView: This view handles retrieving, updating, and deleting a single instance of a model.
  • queryset: This specifies the set of objects that the view will operate on.
  • serializer_class: This specifies the serializer to use for converting the model instances to JSON and vice versa.

Step 5: Defining URLs

Next, we need to define the URLs for our API. In myapp/urls.py:

from django.urls import path
from .views import BookListCreateView, BookDetailView
urlpatterns = [
    path('books/', BookListCreateView.as_view(), name='book-list-create'),
    path('books/<int:pk>/', BookDetailView.as_view(), name='book-detail'),
]

Then, include these URLs in the project’s urls.py (in myproject/urls.py):

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.urls')),
]

Step 6: Testing the API

  1. Run the Development Server:
ython manage.py runserver

2. Access the API:

  • Go to http://127.0.0.1:8000/api/books/ to see the list of books or create a new one.
  • Go to http://127.0.0.1:8000/api/books/1/ to view, update, or delete a specific book.

3. Add Data via Django Admin:

  • Register the Book model in myapp/admin.py:
from django.contrib import admin
from .models import Book

admin.site.register(Book)
  • Create a superuser:
python manage.py createsuperuser
  • Log in to the admin panel (http://127.0.0.1:8000/admin/) and add some books.

Step 7: Testing with Postman or Curl

You can use tools like Postman or curl to test your API endpoints.

  1. Create a Book:
  • curl -X POST -H “Content-Type: application/json” -d ‘{“title”: “1984”, “author”: “George Orwell”, “published_date”: “1949–06–08”, “isbn”: “9780451524935”}’ http://127.0.0.1:8000/api/books/
curl -X POST -H "Content-Type: application/json" -d '{"title": "1984", "author": "George Orwell", "published_date": "1949-06-08", "isbn": "9780451524935"}' http://127.0.0.1:8000/api/books/

2. Get All Books:

curl http://127.0.0.1:8000/api/books/

3. Get a Specific Book:

curl http://127.0.0.1:8000/api/books/1/

4. Update a Book:

curl -X PUT -H "Content-Type: application/json" -d '{"title": "1984", "author": "George Orwell", "published_date": "1949–06–08", "isbn": "9780451524935"}' http://127.0.0.1:8000/api/books/1/

5. Delete a Book:

curl -X DELETE http://127.0.0.1:8000/api/books/1/

Summary

In this lesson, we:

  1. Created a Django model (Book).
  2. Created a serializer (BookSerializer) to convert the model into JSON.
  3. Created views to handle API requests (BookListCreateView and BookDetailView).
  4. Defined URLs for the API.
  5. Tested the API using the Django development server and tools like Postman or curl.

By following these steps, you now have a basic understanding of how serializers work in Django REST Framework and how they can be used to build RESTful APIs. In the next lesson, we will explore more advanced features of serializers, such as custom validation and nested serializers.