Defining Models
Now for the post app, we need some models. A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL of Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating, or any other stuff related to the database. Django models simplify the tasks and organize tables into models. Generally, each model maps to a single database table.
Syntax:
from django.db import models class ModelName(models.Model): field_name = models.Field(**options)
Example:
Python3
from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length = 255 ) author = models.ForeignKey(User, on_delete = models.CASCADE) body = models.TextField() created_on = models.DateTimeField(default = timezone.now) last_modified = models.DateTimeField(auto_now = True ) def __str__( self ) - > str : return self .title |
In the above model, each field represents a column in the SQLite database. We have also created a foreign key for the User model. The user model comes built-in with Django.
Note: The on_delete=models.CASCADE command will delete all the posts of an author if the profile for that author is deleted.
Whenever we create a Model, Delete a Model, or update anything in any of models.py of our project. We need to run two commands makemigrations and migrate. makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created app’s model which you add in installed apps whereas migrate executes those SQL commands in the database file.
So when we run,
python manage.py makemigrations
SQL Query to create the above Model as a Table is created. We can see this under the migrations folder as 0001_initial.py.
To create the table in the database type
python manage.py migrate
Now we have created a model we can perform various operations such as creating a Row for the table or in terms of Django Creating an instance of Model. To know more visit – Django Basic App Model – Makemigrations and Migrate.
Getting started with Django
Python Django is a web framework that is used to create web applications very efficiently and quickly. Django is called a battery included framework because it contains a lot of in-built features such as Django Admin Interface, default database – SQLite3, etc. Django provides various ready-made components such as a way to handle user authentication, a management panel for your website, forms, a way to upload files, etc.
In this article, we will learn Django by creating a basic blogging web application.