Junior — Middle
Explain what is meant by a model in Django and how it is used in application development.
sobes.tech AI
Answer from AI
In Django, a model is a class that describes the data structure and the logic for interacting with the database. Models are defined as subclasses of django.db.models.Model and contain fields corresponding to the columns of a table in the database.
A model is used for:
- Defining the database schema through fields (CharField, IntegerField, etc.).
- Creating, reading, updating, and deleting records in the database via ORM (Object-Relational Mapping).
- Validating data and defining business logic related to the data.
Example of a model in Django:
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
in_stock = models.BooleanField(default=True)
def __str__(self):
return self.name
Thus, the model serves as a link between the application and the database, allowing data to be worked with at the Python object level.