Last Updated : 12 Jul, 2025
A Django model is a Python class that represents a database table. Models make it easy to define and work with database tables using simple Python code. Instead of writing complex SQL queries, we use Django’s built-in ORM (Object Relational Mapper), which allows us to interact with the database in a more readable and organized way.
Key benefits of using Django models:Example
Python
from django.db import models
class GeeksModel(models.Model):
title = models.CharField(max_length = 200)
description = models.TextField()
This program defines a Django model called "GeeksModel" which has two fields:
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 Model1. 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. Before starting to use a model let's check how to start a project and create an app name geeksApp.
Refer to the following articles to check how to create a project and an app in Django.
2. In your app’s 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:
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 MigrationsWhenever we create a Model, Delete a Model, or update anything in any of models.py of our project. We need to run the following two commands
python manage.py makemigrations
python manage.py migrate
Registering Models in Django AdminTo know about Migrations in detail, visit: Basic App Model – Makemigrations and Migrate
To manage your model via the admin interface:
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.
Basic CRUD Operations Using Django ORMTo check more on rendering models in django admin, visit - Render Model in Django Admin Interface
Django lets us interact with its database models, i.e. add, delete, modify and query objects, using a database-abstraction API called ORM(Object Relational Mapper). We can access the Django ORM by running the following command inside our project directory.
1. Adding Objectspython manage.py shell
To create an object of model Album and save it into the database, we need to write the following command:
Python
a = GeeksModel(
title="GeeksForGeeks",
description="A description here",
img="geeks/abc.png"
)
a.save()
2. Retrieving Objects
To retrieve all the objects of a model, we write the following command:
3. Modifying existing ObjectsGeeksModel.objects.all()
We can modify an existing object as follows:
4. Delete an Objecta = GeeksModel.objects.get(id=3)
a.title = "Updated Title"
a.save()
To delete a single object, we need to write the following commands:
a = GeeksModel.objects.get(id=2)
a.delete()
Validation on Fields in a ModelTo check detailed post of Django's ORM (Object) visit Django ORM – Inserting, Updating & Deleting Data
Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. For example, IntegerField comes with built-in validation that it can only store integer values and that too in a particular range.
Enter the following code into models.py file of geeks app.
from django.db import models
from django.db.models import Model
class GeeksModel(Model):
geeks_field = models.IntegerField()
def __str__(self):
return self.geeks_field
After running makemigrations and migrate on Django and rendering above model, let us try to create an instance using string "GfG is Best".
You can see in the admin interface, one can not enter a string in an IntegerField. Similarly every field has its own validations. To know more about validations visit, Built-in Field Validations – Django Models
Django Model data types and fields listRead next: Basic App Model – Makemigrations and Migrate
The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. Here is a list of all Field types used in Django.
Field Name Description AutoField It An IntegerField that automatically increments. BigAutoField It is a 64-bit integer, much like an AutoField except that it is guaranteed to fit numbers from 1 to 9223372036854775807. BigIntegerField It is a 64-bit integer, much like an IntegerField except that it is guaranteed to fit numbers from -9223372036854775808 to 9223372036854775807. BinaryField A field to store raw binary data. BooleanField A true/false field.Django also defines a set of fields that represent relations.
Field Name Description ForeignKey A many-to-one relationship. Requires two positional arguments: the class to which the model is related and the on_delete option. ManyToManyField A many-to-many relationship. Requires a positional argument: the class to which the model is related, which works exactly the same as it does for ForeignKey, including recursive and lazy relationships. OneToOneField A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True, but the “reverse” side of the relation will directly return a single object. Field OptionsField Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to CharField will enable it to store empty values for that table in relational database.
Here are the field options and attributes that an CharField can use.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4