Django ORM if you already know SQL

If you are migrating to Django from another MVC framework, chances are you already know SQL.

In this post, I will be illustrating how to use Django ORM by drawing analogies to equivalent SQL statements. Connecting a new topic to your existing knowledge will help you learn to use the ORM faster.

Let us consider a simple base model for a person with attributes name, age, and gender.

t7fs6oc

To implement the above entity, we would model it as a table in SQL.

The same table is modeled in Django as a class which inherits from the base Model class. The ORM creates the equivalent table under the hood.

 

The most used data types are:

SQL Django
INT IntegerField()
VARCHAR(n) CharField(max_length=n)
TEXT TextField()
FLOAT(n) FloatField()
DATE DateField()
TIME TimeField()
DATETIME DateTimeField()

The various queries we can use are:

SELECT Statement

Fetch all rows
SQL:

Django:

Fetch specific columns
SQL:

Django:

etch distinct rows
SQL:

Django:

Fetch specific number of rows
SQL:

Django:

LIMIT AND OFFSET keywords
SQL:

Django:

 

WHERE Clause

Filter by single column
SQL:

Django:

Filter by comparison operators
SQL:

Django:

BETWEEN Clause
SQL:

Django:

LIKE operator
SQL:

Django:

IN operator
SQL:

Django:

 

ANDOR and NOT Operators

SQL:

Django:

SQL:

Django:

SQL:

Django:

 

https://amitness.com/2018/10/django-orm-for-sql-users/