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
<your_path>/backend/restapi
(venv) $ python manage.py makemigrations quotes
Migrations for 'quotes':
  quotes/migrations/0001_initial.py
    - Create model Quote
(venv) $ ls quotes/migrations/
0001_initial.py __init__.py     __pycache__

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

(venv) $ python manage.py 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 manage.py 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              
auth_user_user_permissions
sqlite> .schema --indent quotes_quote
CREATE TABLE IF NOT EXISTS "quotes_quote"(
  "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  "text" varchar(200) NOT NULL,
  "author" varchar(100) NULL,
  "image_url" varchar(200) NULL
);
sqlite> 

Now, let’s check out our serializer class :

(venv) $ python manage.py 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.
(InteractiveConsole)
>>> from quotes.serializers import QuoteSerializer
>>> serializer = QuoteSerializer()
>>> print(serializer)
QuoteSerializer():
    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 : https://github.com/hpin2019/coding-sessions/tree/master/drf-tutorial-1

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: