Templates in Django are the cornerstone for building systems with Python and Django. They are the high-level representation of the database, allowing you to create, retrieve, update, and delete records without having to manually write SQL. Instead, Django does all the heavy lifting for you, letting you focus on your application logic.
To start working with models in Django, you first need to create a model. A model is a Python class that inherits from django.db.models.Model
. Each attribute of the class represents a field in the database. For example:
from django.db import models class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE) published_on = models.DateField()
In this example, we create a Book template with three fields: title, author, and published_on. The title field is a text field with a maximum length of 200 characters. The author field is a foreign key to the Author model, which means that each book is associated with an author. The published_on field is a date.
Once you've defined your models, you need to tell Django to create the corresponding tables in the database. This is done using Django's migration command:
python manage.py makemigrations python manage.py migrate
These commands will generate and apply the necessary migrations to create the tables in the database.
Once the tables are in place, you can start working with the data. Django provides a high-level database API that allows you to create, retrieve, update, and delete records in a Pythonic way. For example, to create a new book, you would do the following:
book = Book(title='Python for Beginners', author=author, published_on='2021-01-01') book.save()
To retrieve a book from the database, you can use the get
:
book = Book.objects.get(title='Python for Beginners')
To update a record, you simply change the object's attributes and call the save
method again:
book.title = 'Python for Professionals' book.save()
And to delete a record, you use the delete
method:
book.delete()
In addition, Django supports complex database queries using the filter
method. For example, to find all books published in 2021, you would do the following:
books = Book.objects.filter(published_in__year=2021)
In short, models in Django are a powerful tool for working with databases. They allow you to create, retrieve, update and delete records in a Pythonic way, without having to worry about SQL. This makes building systems with Python and Django much easier and more enjoyable.