Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Serializers in Django REST Framework

Tech May 10 16

Django REST framework serializers are defined as classes that inherit from rest_framework.serializers.Serializer. For example, given a dataabse model Book:

class Book(models.Model):
    title = models.CharField(max_length=50, verbose_name='Title')
    pub_date = models.DateField(verbose_name='Publication Date', null=True)
    reads = models.IntegerField(default=0, verbose_name='Read Count')
    comments = models.IntegerField(default=0, verbose_name='Comment Count')
    cover = models.ImageField(upload_to='covers', verbose_name='Cover Image', null=True)

We can create a corresponding serializer:

class BookSerializer(serializers.Serializer):
    """Book data serializer"""
    id = serializers.IntegerField(label='ID', read_only=True)
    title = serializers.CharField(label='Title', max_length=50)
    pub_date = serializers.DateField(label='Publication Date', required=False)
    reads = serializers.IntegerField(label='Read Count', required=False)
    comments = serializers.IntegerField(label='Comment Count', required=False)
    cover = serializers.ImageField(label='Cover Image', required=False)

Field Types and Options

Common field types include:

  • BooleanField, CharField, EmailField
  • IntegerField, FloatField, DecimalField
  • DateTimeField, DateField, TimeField
  • FileField, ImageField
  • ListField, DictField

Field options include:

  • max_length, min_length
  • allow_blank, trim_whitespace
  • max_value, min_value
  • read_only, write_only
  • required, default

Creating Serializer Objects

Serializer constructor:

Serializer(instance=None, data=empty, **kwargs)

Example usage:

book = Book.objects.get(id=1)
serializer = BookSerializer(book)
serializer.data

For querysets:

books = Book.objects.all()
serializer = BookSerializer(books, many=True)
serializer.data

Related Object Nesting

Several approaches for handling related objects:

  1. PrimaryKeyRelatedField:
publisher = serializers.PrimaryKeyRelatedField(queryset=Publisher.objects.all())
  1. StringRelatedField:
publisher = serializers.StringRelatedField()
  1. Nested serializers:
publisher = PublisherSerializer()

Deserialization and Validation

Validation methods:

  1. Field-level validation:
def validate_title(self, value):
    if 'django' not in value.lower():
        raise serializers.ValidationError("Book must be about Django")
    return value
  1. Object-level validatino:
def validate(self, data):
    if data['reads'] < data['comments']:
        raise serializers.ValidationError("Read count cannot be less than comments")
    return data
  1. Validators:
def about_django(value):
    if 'django' not in value.lower():
        raise serializers.ValidationError("Book must be about Django")

class BookSerializer(serializers.Serializer):
    title = serializers.CharField(validators=[about_django])

ModelSerializer

Automaticlaly generates serializers from models:

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'

Customization options:

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'title', 'pub_date')
        read_only_fields = ('id',)
        extra_kwargs = {
            'reads': {'min_value': 0},
            'comments': {'min_value': 0}
        }
Tags: Djangorest

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.