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.
Models
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 modelsclass 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
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 HttpResponsedef my_view(request):if request.method == ‘GET’:# <view logic>return HttpResponse(‘result’)
As a class:
from django.http import HttpResponsefrom django.views import Viewclass MyView(View):def get(self, request):# <view logic>return HttpResponse(‘result’)
Serializers
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 datetimeclass Comment(object):def __init__(self, email, content, created=None):self.email = emailself.content = contentself.created = created or datetime.now()comment = Comment(email=’[email protected]’, content=’foo bar’)from rest_framework import serializersclass CommentSerializer(serializers.Serializer):email = serializers.EmailField()content = serializers.CharField(max_length=200)created = serializers.DateTimeField()serializer = CommentSerializer(comment)serializer.data# {‘email’: ‘[email protected]’, ‘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 JSONRendererjson = JSONRenderer().render(serializer.data)json# b’{“email”:”[email protected]”,”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
In short, in this article, we shared about models, views and serializers and what each one represents.
Hope this has given you a succinct and straightforward overview of some of the key elements of frontend-backend interactions!
This article first appeared at 9cv9 Medium repo here.