django create table from model

django create table from model

Django made creating the tables in the database very simple with its built-in ORM. To create table in the database with django is to create a django model with all required fields and then create migrations and apply them. Let's jump-in learn how to create database table with django model.

Creating database table with django model

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    address = models.TextField()

With the above code we are creating the table named "person" with fields "first_name", "last_name" and "address". The equivallent "SQL" for above django model is

CREATE TABLE <app name>_person (
    id int,
    first_name varchar(100),
    last_name varchar(100),
    address text,
);

As we know django comes with ORM(Object Relational Mapper) so, we do not need to write SQL queries to deal with the database. We write database queries in django and django ORM converts all these queries into equivalent SQL and performs the query on the database and returns the results.

In the above code we have imported the "models" module which contains the functionality related to database(i.e ORM). "models.Model" is a base class for all model classes in django application. Each model class represents a database table.

Create migrations for above django model

To create migrations for the django application we have to run the below command.

python manage.py makemigrations <app name>

above command will create migrations for the model in the directory "migrations" under the application directory.

Apply migrations to create table in the database

To create table in the database for our django application we have to apply above created models using below command

python manage.py migrate <app name>

After running above command it creates the table in the database. To write django models we need to know the different fields provided by django to use correct field for the table.

That's it folks it's pretty easy to create django model.