Relationships
-
In relational database, there can be the following types of relations
- one to one
- Many to one
- Many to Many
-
Many to One:
- Consider the data about employees belonging to different departments stored in a table
employee
with their employee ID as primary key alongside a column that stores a department, this table also contains a colum that stores departments deopartment id.
class Department(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=255) class Employee(models.Model): name = models.CharField(max_length=50) email = models.EmailField(help_text="Email id of the employee") department = models.ForeignKey(Department, on_delete=models.CASCADE)
- Many to Many:
- models.ManyToManyField
- One to One:
- Python django has models.OneToOneField
- Consider the data about employees belonging to different departments stored in a table
Migration Commands
- Make migrations which would create a file in migrations folder
python manage.py makemigrations <appname>
- to view the migrations
python manage.py showmigrations
- To understand the sql equivalent commands generated by migration
python manage.py sqlmigrate <app_name> <generated_file>
python manage.py sqlmigrate books 0001_inital
- To apply the changes to the database
python manage.py migrate <appname>
Django’s Database CRUD Operations
- Django ORM provides the capability to deal with the CRUD operations without dealing SQL Statements.
- To do this lets enter the python Django’s shell
- Execute
python manage.py shell
- Now view the table in DB Browser
- Now try to write the following in the shell
Publisher.objects.get()
Publisher.objects.all()