Django Models

Yashwanth
django Launcher
Published in
4 min readJul 1, 2020

--

Outline

Django Models are basically empty data containers which are implemented to store data accordingly. They are loaded with extensible feature set in the name of modules which allows us to gather data of our choice.

Django’s model makes use of a powerful ORM layer which simplifies dealing with the database and the data and accelerates the development process.

Without Object-Relational-Mapping, developers would have to create the tables themselves and define the queries or procedures which sometimes translates to the hefty amount of SQL that is prone to be complex and hard to track.

The ORM layer lets you write all the table definitions in simple python code, and it takes care of translating that to the appropriate query language chosen, and it also facilitates the CRUD operations.

In fact, the developer doesn’t necessarily need to know the complex SQL altogether or what it translates to, though, it worth noting that understanding SQL would allow you to write better and faster queries and also make your website more secure.

Django supports many database systems. SQLite is really good for testing and development because it could be used right out of the box without having to install further software. For production, you can go for MYSQL or PostgreSQL, and if you’re looking for a NoSQL database, you can use MongoDB with Django.

Unlike other frameworks, the models are all placed in one file, conventionally, models.py, which might make it feel crowded for bigger projects. To avoid this, we can categorise apps in a project, thereby drafting the required model for a specific app.

Generally, each model maps to a single database table. Each model is a Python class. Attributes in the model represents database fields (columns).

Various practices for accessing and creating models made django a unique web-framework and most popular.

Start a project; create an app.

For Example., if we want to gather first_name and last_name from the end-user we need to start with an application.

What’s the difference between a project and an app? An app is a Web application that does something — e.g., for logging-in we need user_id and pwd or so, we can maintain an app so that the respective app will only collect the user_id and pwd. A project is a collection of configuration of apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

$ python manage.py startapp myapp

Each and every time when you start a new app there will be a “models.py” file inside the app directory.

myapp/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py

In order to gather the first_name and last_name of a Person, we can create a simple model as follows…

from django.db import models

class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)

first_name and last_name are fields of the model. Each field is specified as a class attribute, and each attribute maps to a database column.

The above Person model would create a database table like this:

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

The name of the table, myapp_person, is automatically derived from some model metadata but can be overridden

An id field is added automatically, but this behavior can be overridden

Now our database table Person is ready with fields first_name and last_name

Once you have defined your models(i.e., tables), you need to tell Django you’re going to use those models. Do this by editing your settings file and changing the INSTALLED_APPS setting to add the name of the module that contains your models.py.

For example, if the models for your application live in the module myapp.models then in the settings.py file we must add “myapp”.

INSTALLED_APPS = [
#...
'myapp',
#...
]

Now our myapp → models is ready to capture the data.

Flowing data into these models will be demonstrated in another article. Upto this point we have demonstrated how Django framework is allowed to capture the data (i.e., through Models).

Fields

The most important part of a model — and the only required part of a model — is the list of database fields it defines. Fields are specified by class attributes.

Example:

from django.db import models

class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)

class Album(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()
  • The column type, which tells the database what kind of data to store (e.g. INTEGER, VARCHAR, TEXT).

Django ships with dozens of built-in field types; you can find the complete list here.

You can easily write your own fields if Django’s built-in ones don’t do the trick; refer here.

We can even construct relationships among various models which is an advance concept will be demonstrated in coming articles.

These are the basic learning procedures to understand the way models are used. If you neglect practicing these steps and rush to develop heavy applications, you will be running into situations like…

…and…you will be messing it up(for sure!)

I have created a cool presentation on Django Models here.

Cheers..!

--

--