Django Models And Migrations

In Django,

Models are used to define the database models. To apply these models we need run migration. Migration is used to allow us to make any changes to our database even after it was created and the data in that database. It acts like version control of our database and also used to manually it generates SQL queries.

Run this command after modifying your models:

python manage.py makemigrations

To update the database schema, run:

python manage.py migrate

This executes the migration file and modifies the database accordingly. Django ORM is a Object Relational Mapping is a built in that you to allow ta interact with database using python code instead of using SQL queries.

For ex: Creating Records (INSERT)

In SQL:

INSERT INTO post (title, content, author_id) VALUES ('My First Post', 'This is Django ORM', 1);
post = Post(title="My First Post", content="This is Django ORM", author=user)
post.save()
python manage.py shell

Django Shell is an environment where you run Django ORM queries directly in the terminal without writing a script. The main thing is it allows direct interaction with Django models using python.

For ex: Retrieve the data from the model.

from blog.models import Post 

posts = Post.objects.all()
print(posts)