Django ORM: Mapping Models to Database
In Django, you can map the database by defining model classes. Here is a simple example:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
publish_date = models.DateField()
price = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return self.title
In the example above, we defined a model class named Book that inherits from models.Model. Each property in the model class will be mapped to a field in the database table. For instance, the title property is mapped to a field of type CharField, and the price property is mapped to a field of type DecimalField.
To map this model class to the database, you can execute the following command:
python manage.py makemigrations
python manage.py migrate
This will create a table in the database named “book” with four fields: title, author, publish_date, and price.
By using this method, we can manipulate the database using Django’s ORM without the need to directly write SQL statements. The ORM in Django offers many convenient methods for querying, inserting, updating, and deleting database records.