Models and Migrations
- Web applications constantly interact with databases and one way of doing it is using SQL.
- Django provides a level of abstraction using which we can easily work with databases using ORM (Object Relation Mapping) called as
- Django ORM converts object-oriented Python code into actual database constructs such as tables with data type definitions and facilitates all the database operations via simple Python.
- Because of this , we do not have to deal with SQL commands while performing database operations.
- This helps in faster application development and ease in maintaining application source code.
- Django supports relational databases such as SQLite, PostgreSQL, Oracle Database and MySQL
- Django database abstraction layers ensures the same python/Django code can be used across any of the above mentioned database.
- By default Django project is configured to SQLite.
Database Configurations and Creating Django Applications
- The database configurations will be present in settings.py Refer Here
- Django project can have multiple apps that often act as discrete entities. Django comes with the following apps by default Refer Here
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]
- Django ORM helps make database operations simpler and major part of the operation is to transform the Python code into database structures such as database files with started data types and tables.
- This transformation of Python code into database structures is known as migrations
- Since we have a Djnago project setup lets perform our first migration by exeucting the following command in terminal
python manage.py migrate
- Lets ensuer we have DB Browser for SQLite Refer Here
Creating Django Models and Migration
- A Django model is a Python class that holds the bluepring for creating a table in a database.
- The models.py file can have many such models and each model transforms into a database table.
- Refer Here for the official docs on creating Models
Foreign Key On delete
There are seven possibilites
- CASCADE: When the referenced object is delete, also delete the object which you have references to. SQL equivalent: CASCADE
- PROTECT: Forbid the deletion of referenced object
- RESTRICT: Similar behavior as PROTECT django raises RESTRICT error
- SET_NULL: Set the reference to NULL
- SET_DEFAULT: Set the default Value
- SET(…): Set a given value
Refer Here for the official documentation
- Create tables in database (SQL) of choice to represent many to many relationship b/w two tables Book and Author.
- Also ensure you have insert, select queries for this.