A Django model is a Python class that represents a database table. It allows developers to interact with the database easily using Python code instead of writing raw SQL. Models leverage Django’s ORM (Object Relational Mapper) to handle data in a readable and organized way.
Key Benefits of Django Models:
- Simplifies database operations like creating, updating, and deleting records.
- Automatically generates SQL queries behind the scenes.
- Integrates with Django’s admin interface for easy data management.
- Provides built-in validations and metadata handling.
- Supports relationships between tables (like ForeignKey, ManyToManyField).
Example:
Python
from django.db import models
class GeeksModel(models.Model):
title = models.CharField(max_length = 200)
description = models.TextField()
This defines a Django model called "GeeksModel" which has two fields:
- title: A character field with a 200-character limit.
- description: A text field for longer input.
This model creates a corresponding table in the database when migrations are applied. Django maps the fields defined in Django models into table fields of the database as shown below.
Creating a Django Model
To create Django Models, one needs to have a project and an app working in it. After you start an app you can create models in app_name/models.py.
In models.py file, define your model like this:
Python
from django.db import models
class GeeksModel(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
last_modified = models.DateTimeField(auto_now_add=True)
img = models.ImageField(upload_to="images/")
def __str__(self):
return self.title
This code defines a new Django model called "GeeksModel" which has four fields:
- title: a character field with a maximum length of 200.
- description: a text field.
- last_modified: a date and time field that automatically sets the date and time of creation.
- img: tores image uploads in the images/ directory.
- __str__ method is also defined to return the title of the instance of the model when the model is printed.
This code does not produce any output. It is defining a model class which can be used to create database tables and store data in Django.
Applying Migrations
Whenever you create, delete, or update a model in your project’s models.py, you need to run the following commands:
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.
- makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created app's model which you add in installed apps.
- migrate executes those SQL commands in the database file.
Registering Models in Django Admin
To manage your model via the admin interface:
- Open admin.py in your app directory.
- Register your model:
Python
from django.contrib import admin
# Register your models here.
from .models import GeeksModel
admin.site.register(GeeksModel)
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.
We can now use the admin panel to create, update, and delete model instances.
Model Field Types
Django models consist of fields that define the structure of database tables. Each field specifies:
- The type of data it stores (text, numbers, dates, files, etc.)
- Constraints and validations on the data
Common field types include:
- CharField: Stores short text (like names or titles)
- TextField: Stores large amounts of text (like descriptions)
- IntegerField: Stores integer values
- BooleanField: Stores True/False values
- DateTimeField: Stores date and time
- ImageField / FileField: Stores images or files
Fields not only define how data is stored, but also automatically handle validation and form generation when used in Django forms.
Relationship Fields
Relationship fields are used when models are related to each other. They allow you to represent one-to-one, one-to-many, and many-to-many relationships in your database. Common relationship fields:
- ForeignKey: Many-to-one relationship.
- OneToOneField: One-to-one relationship.
- ManyToManyField: Many-to-many relationship.
Relationship fields allow easy querying of related objects using Django ORM and automatically handle database constraints.
Field Options
Every field in Django models can have options (attributes) to control its behavior.
Field options allow you to:
- Set constraints (null, blank, unique)
- Provide default values (default)
- Customize display names (verbose_name)
- Add help text for forms (help_text)
- Apply validators to enforce custom rules
These options make Django models highly flexible and ensure data integrity in the database and forms.
Basic CRUD Operations Using Django ORM
Django’s Object-Relational Mapper (ORM) allows interaction with the database using Python code instead of raw SQL.
With the ORM, the four basic operations on models are:
- Create: Add new records to the database and save them.
- Retrieve: Query and fetch existing records easily.
- Update: Modify existing records and save the changes.
- Delete: Remove records safely from the database
The ORM abstracts away SQL commands, making database operations more readable, organized, and consistent across different databases.
Defining models and fields
Create Model in Django
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice