Skip to content

Django REST Framework – Models and Serializers

Part 4 of 8 in the series Django REST Framework




After our app is added in settings.py in previous post, Let’s create our first DRF Model for our app. We will create a Quote model which has quote text, author and image url.

You can get all the files related to the examples here : https://github.com/hpin2019/coding-sessions/tree/master/drf-tutorial-1

(venv) $ pwd
<your_path>/backend/restapi
(venv) $ vi quotes/models.py 

Add following code for model :

from django.db import models
# Create your models here.

class Quote(models.Model):
    text = models.CharField(max_length=200, blank=False, null=False)
    author = models.CharField(max_length=100, blank=True, null=True)
    image_url = models.CharField(max_length=200,blank=True,null=True)

We have added three fields :text, author and image_url, all of them are text.

Now add a serializer for the model in new serializers.py file

(venv) $ vi quotes/serializers.py 
from quotes.models import Quote
from rest_framework import serializers


class QuoteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Quote
        fields = '__all__'

This will create a ready serializer class for us based on Quotes Model. In next post, we will create DB Migrations and test our serializers.

Series Navigation<< Creating Django Project and AppDRF – DB Migrations and Serializers testing >>
Published inDjango

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: