Skip to content

DRF – DB Migrations and Serializers testing

Part 5 of 8 in the series Django REST Framework

Django migrations make your life easy by automatically defining SQL tables for your models. Django comes with ORM (Object-Relational-Mapper) for this and Fields defined in model are mapped to Columns in SQL table.

So whenever you create a new model or change an existing model, you should do migration. Django will create python scripts for migrations which you can store in your source repo for tracking DB changes over time and it’s helpful for your code update in production.

(venv) $ pwd
(venv) $ python makemigrations quotes
Migrations for 'quotes':
    - Create model Quote
(venv) $ ls quotes/migrations/     __pycache__

Django created file for migrations. Now, let’s run this migration.

(venv) $ python migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, quotes, sessions
Running migrations:
  Applying quotes.0001_initial... OK

Django has now created the DB table for us in SQLite. Let’s check the same using dbshell.

(venv) $ python dbshell
SQLite version 3.24.0 2018-06-04 14:10:15
Enter ".help" for usage hints.
sqlite> .tables
auth_group                  django_admin_log          
auth_group_permissions      django_content_type       
auth_permission             django_migrations         
auth_user                   django_session            
auth_user_groups            quotes_quote              
sqlite> .schema --indent quotes_quote
  "text" varchar(200) NOT NULL,
  "author" varchar(100) NULL,
  "image_url" varchar(200) NULL

Now, let’s check out our serializer class :

(venv) $ python shell
Python 3.7.4 (default, Oct 12 2019, 18:55:28) 
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from quotes.serializers import QuoteSerializer
>>> serializer = QuoteSerializer()
>>> print(serializer)
    id = IntegerField(label='ID', read_only=True)
    text = CharField(max_length=200)
    author = CharField(allow_blank=True, allow_null=True, max_length=100, required=False)
    image_url = CharField(allow_blank=True, allow_null=True, max_length=200, required=False)

We can see that our serializer class is automatically created from our Model.

You can get all the files related to the examples here :

Next we will create Views for our REST API example.

Series Navigation<< Django REST Framework – Models and SerializersDjango REST Framework – Creating Views >>
Published inDjango

Be First to Comment

Leave a Reply

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

%d bloggers like this: