![]() |
VOOZH | about |
A Django model is a Python class that represents a database table. It helps manage data easily using Python instead of writing SQL.
A Django project and app are needed before defining any models. After starting an app, models can be created in the file app_name/models.py.
In models.py:
This defines a Django model called "GeeksModel" which has three fields:
This model is converted into a database table through Django’s migration system, which tracks changes and applies them to the database. Django maps the fields defined in Django models into table fields of the database.
Whenever a model is created, deleted or updated in the project’s models.py file, the following commands must be executed:
python manage.py makemigrations
python manage.py migrate
The migrations system in Django generates and applies the necessary SQL commands to update your database according to the changes in your models.
To manage your model via the admin interface:
This code does not produce any output, it simply registers the "GeeksModel" with the admin site, so that it can be managed via the Django admin interface. The admin panel can now be used to create, update and delete model instances.
Django models consist of fields that define the structure of database tables. Each field specifies:
Common field types include:
Fields not only define how data is stored, but also automatically handle validation and form generation when used in Django forms.
Relationship fields are used when models are related to each other. It allow to represent one-to-one, one-to-many and many-to-many relationships in your database. Common relationship fields:
Relationship fields allow easy querying of related objects using Django ORM and automatically handle database constraints.
Every field in Django models can have options (attributes) to control its behavior. Field options allow you to:
These options make Django models highly flexible and ensure data integrity in the database and forms.
Django's Object-Relational Mapper (ORM) allows interaction with the database using Python code instead of raw SQL. With the ORM, four basic operations on models are:
The ORM abstracts away SQL commands, making database operations more readable, organized and consistent across different databases.