Understanding Models, Views and Serializers in Django

Soo we are back once again this week, talking about models, views and serializers — essentially everything you will need to get an up-and-running database that interacts with your web application.

Put simply, models are the Python representation of your tables.

“A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table.”

Each field in the model generally corresponds to a column in the database. Each field of the model has a specific definition in the sense of the data it stores or the type of field it is. It can be a CharField or IntegerField, a ManytoManyField or a OneToManyField or just be a ForeignKey. We can also define the minimal validation requirements, used in Django’s admin and in automatically-generated forms. It is crucial to remember that these fields are important as they will go on to define our database.

How you may ask?

Well, when you execute the Python command to run migrations, Django performs a system check and creates the necessary tables in the database — Elegant and Neat. (Django also adds a primary key to the it but this can be overridden.)

Example:

from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)

This will lead to the execution of the following query:

CREATE TABLE myapp_person (
“id” serial NOT NULL PRIMARY KEY,
“first_name” varchar(30) NOT NULL,
“last_name” varchar(30) NOT NULL
);

The models documentation in Django is rich, detailed, and offers unlimited possibilities as we;; as customisations to suit every need. I will not go into the nitty-gritty here as I just want to give you a basic overview.

https://docs.djangoproject.com/en/2.2/topics/db/models/

So, moving onto the next integral part of the application is the views.

Views, in the most simplest terms, is just something that will be used to interact with the backend and helps structure your code.

“A view is a callable which takes a request and returns a response. This can be more than just a function, and Django provides an example of some classes which can be used as views.”

Most views that you’ll be using are class-based views and they tend to be the new normal. At its core, a class-based view allows you to respond to different HTTP request methods with different class instance methods, instead of conditionally branching code inside a single view function. They allow you maximum flexibility to design complex interactions and responses to specific method calls. This flexibility comes in the form of mixins, which are essentially just commonly used methods, allowing for multiple inheritance, and emulation of multiple parent classes.

Using functions:

from django.http import HttpResponse
def my_view(request):
if request.method == ‘GET’:
# <view logic>
return HttpResponse(‘result’)

As a class:

from django.http import HttpResponse
from django.views import View
class MyView(View):
def get(self, request):
# <view logic>
return HttpResponse(‘result’)

Serializers are not part of Django but instead of Django-REST (which works in conjunction with the main Django framework). The main function of serializers is to render the available information into formats that can be easily accessible and utilised by the frontend.

“Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then 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 first validating the incoming data.”

Serializers work very similar to the form class in Django framework, and understandably so as they both deal with accessing and mutating data in the database.

You will often use ModelSerializers as these interact directly with a model and query set.

from datetime import datetime
class Comment(object):
def __init__(self, email, content, created=None):
self.email = email
self.content = content
self.created = created or datetime.now()
comment = Comment(email=’leila@example.com’, content=’foo bar’)
from rest_framework import serializers
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
serializer = CommentSerializer(comment)
serializer.data
# {‘email’: ‘leila@example.com’, ‘content’: ‘foo bar’, ‘created’: ‘2016–01–27T15:17:10.375877’}

At this point we’ve translated the model instance into Python native datatypes. To finalise the serialization process we render the data into json.

from rest_framework.renderers import JSONRenderer
json = JSONRenderer().render(serializer.data)
json
# b’{“email”:”leila@example.com”,”content”:”foo bar”,”created”:”2016–01–27T15:17:10.375877"}’

I’ll not be diving deep into deserialization as it’s slightly beyond the scope of this blog post, but if you’re a keen coder like me, simply check out the documentation for more information

Hope this has given you a succinct and straightforward overview of some of the key elements of frontend-backend interactions!

Neil Shah
Neil Shah
I am a final year student at NUS School of Computing pursuing a major in Business Analytics. I am passionate about finance, healthcare and data analytics. I am also well versed in machine learning, having done projects and courses on it. I am someone who loves challenges and venturing down the road less travelled.

Latest posts

Django Periodic Task with Celery Task Queue

Task Queue? Periodic Tasks? What are they? Task Queue is a way of organizing work or tasks in programs asynchronously, without a user’s request, and distribute...

Understanding Models, Views and Serializers in Django

Soo we are back once again this week, talking about models, views and serializers — essentially everything you will need to get an up-and-running...

Creating a Django Web Application with a PostgreSQL Database on Windows

At some point in time, you will foray into the realm of web development. With the many frameworks out there, you may be confused...

More from author

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related posts