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:
- Simplifies database operations like creating, updating, and deleting.
- Automatically generates SQL queries.
- Integrates with Django’s admin interface.
- Provides built-in validations and metadata handling.
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:
- 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
1. 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:
- 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 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
- 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.
To know about Migrations in detail, visit: Basic App Model – Makemigrations and Migrate
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.

To check more on rendering models in django admin, visit - Render Model in Django Admin Interface
Basic CRUD Operations Using Django ORM
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.
python manage.py shell
1. Adding Objects
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:
GeeksModel.objects.all()
3. Modifying existing Objects
We can modify an existing object as follows:
a = GeeksModel.objects.get(id=3)
a.title = "Updated Title"
a.save()
4. Delete an Object
To delete a single object, we need to write the following commands:
a = GeeksModel.objects.get(id=2)
a.delete()
To check detailed post of Django's ORM (Object) visit Django ORM – Inserting, Updating & Deleting Data
Validation on Fields in a Model
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.
Python
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
Read next: Basic App Model – Makemigrations and Migrate
Django Model data types and fields list
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. The default form widget for this field is a CheckboxInput. |
CharField | It is string filed for small to large-sized input |
DateField | A date, represented in Python by a datetime.date instance |
| It is used for date and time, represented in Python by a datetime.datetime instance. |
DecimalField | It is a fixed-precision decimal number, represented in Python by a Decimal instance. |
DurationField | A field for storing periods of time. |
EmailField | It is a CharField that checks that the value is a valid email address. |
FileField | It is a file-upload field. |
FloatField | It is a floating-point number represented in Python by a float instance. |
ImageField | It inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image. |
IntegerField | It is an integer field. Values from -2147483648 to 2147483647 are safe in all databases supported by Django. |
GenericIPAddressField | An IPv4 or IPv6 address, in string format (e.g. 192.0.2.30 or 2a02:42fe::4). |
NullBooleanField | Like a BooleanField, but allows NULL as one of the options. |
PositiveIntegerField | Like an IntegerField, but must be either positive or zero (0). |
PositiveSmallIntegerField | Like a PositiveIntegerField, but only allows values under a certain (database-dependent) point. |
SlugField | Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs. |
SmallIntegerField | It is like an IntegerField, but only allows values under a certain (database-dependent) point. |
TextField | A large text field. The default form widget for this field is a Textarea. |
TimeField | A time, represented in Python by a datetime.time instance. |
URLField | A CharField for a URL, validated by URLValidator. |
UUIDField | A field for storing universally unique identifiers. Uses Python’s UUID class. When used on PostgreSQL, this stores in a uuid datatype, otherwise in a char(32). |
Relationship Fields
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 Options
Field 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.
Field Options | Description |
---|
Null | If True, Django will store empty values as NULL in the database. Default is False. |
Blank | If True, the field is allowed to be blank. Default is False. |
db_column | The name of the database column to use for this field. If this isn’t given, Django will use the field’s name. |
Default | The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created. |
help_text | Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form. |
primary_key | If True, this field is the primary key for the model. |
editable | If False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True. |
error_messages | The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. |
help_text | Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form. |
verbose_name | A human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces. |
validators | A list of validators to run for this field. See the validators documentation for more information. |
Unique | If True, this field must be unique throughout the table. |
Similar Reads
Django Tutorial | Learn Django Framework Django is a Python framework that simplifies web development by handling complex tasks for you. It follows the "Don't Repeat Yourself" (DRY) principle, promoting reusable components and making development faster. With built-in features like user authentication, database connections, and CRUD operati
10 min read
Django Basics
Django BasicsDjango is a Python-based web framework which allows us to quickly develop robust web application without much third party installations. It comes with many built-in featuresâlike user authentication, an admin panel and form handlingâthat help you build complex sites without worrying about common web
3 min read
Django Installation and SetupInstalling and setting up Django is a straightforward process. Below are the step-by-step instructions to install Django and set up a new Django project on your system.Prerequisites: Before installing Django, make sure you have Python installed on your system. How to Install Django?To Install Django
2 min read
When to Use Django? Comparison with other Development StacksPrerequisite - Django Introduction and Installation Django is a high-level Python web framework which allow us to quickly create web applications without all of the installation or dependency problems that we normally face with other frameworks. One should be using Django for web development in the
2 min read
Django Project MVT StructureDjango follows the MVT (Model-View-Template) architectural pattern, which is a variation of the traditional MVC (Model-View-Controller) design pattern used in web development. This pattern separates the application into three main components:1. ModelModel acts as the data layer of your application.
2 min read
How to Create a Basic Project using MVT in Django ?Prerequisite - Django Project MVT Structure Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server. Create a basic Project: To in
2 min read
How to Create an App in Django ?In Django, an app is a web application that performs a specific functionality, such as blog posts, user authentication or comments. A single Django project can consist of multiple apps, each designed to handle a particular task. Each app is a modular and reusable component that includes everything n
3 min read
Django settings file - step by step ExplanationOnce we create the Django project, it comes with a predefined Directory structure having the following files with each file having its own uses. Let's take an example // Create a Django Project "mysite" django-admin startproject mysite cd /pathTo/mysite // Create a Django app "polls" inside project
3 min read
Django view
Views In Django | PythonDjango Views are one of the vital participants of the MVT Structure of Django. As per Django Documentation, A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, a redirect, a 404 error, an XML document, an ima
6 min read
Django Function Based ViewsDjango is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks. Django is based on MVT (Model View Template) architecture and revolves around CRUD (Create, Retrieve, Up
7 min read
Django Class Based ViewsClass-Based Views (CBVs) allow developers to handle HTTP requests in a structured and reusable way. With CBVs, different HTTP methods (like GET, POST) are handled as separate methods in a class, which helps with code organization and reusability.Advantages of CBVsSeparation of Logic: CBVs separate d
6 min read
Class Based vs Function Based Views - Which One is Better to Use in Django?Django, a powerful Python web framework, has become one of the most popular choices for web development due to its simplicity, scalability and versatility. One of the key features of Django is its ability to handle views and these views can be implemented using either Class-Based Views (CBVs) or Fun
6 min read
Django Templates Templates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the ba
7 min read
Django Static File Static Files such as Images, CSS, or JS files are often loaded via a different app in production websites to avoid loading multiple stuff from the same server. This article revolves around, how you can set up the static app in Django and server Static Files from the same.Create and Activate the Virt
3 min read
Django Model
Django Forms
Django FormsDjango Forms are used to gather input from users, validate that input, and process it, often saving the data to the database. For example, when registering a user, a form collects information like name, email, and password.Django automatically maps form fields to corresponding HTML input elements. I
5 min read
How to Create a form using Django FormsThis article explains how to create a basic form using various form fields and attributes. Creating a form in Django is very similar to creating a model, you define the fields you want and specify their types. For example, a registration form might need fields like First Name (CharField), Roll Numbe
2 min read
Django Form | Data Types and FieldsWhen collecting user input in Django, forms play a crucial role in validating and processing the data before saving it to the database. Django provides a rich set of built-in form field types that correspond to different kinds of input, making it easy to build complex forms quickly.Each form field t
4 min read
Django Form | Build in Fields ArgumentWe utilize Django Forms to collect user data to put in a database. For various purposes, Django provides a range of model field forms with various field patterns. The most important characteristic of Django forms is their ability to handle the foundations of form construction in only a few lines of
3 min read
Python | Form validation using djangoPrerequisites: Django Installation | Introduction to DjangoDjango works on an MVT pattern. So there is a need to create data models (or tables). For every table, a model class is created. Suppose there is a form that takes Username, gender, and text as input from the user, the task is to validate th
5 min read
Render Django Form Fields ManuallyDjango form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). We have already covered on How to create and use a form in Django?. A form comes with 3 in-built methods that can be used to ren
5 min read
Django URLS
Django Admin Interface - Python Prerequisites: Django Introduction and Installation Creating a ProjectThe Django Admin Interface is one of the most powerful features of the Django framework. It provides a ready-to-use interface for managing project data through models, allowing developers and site administrators to perform Create,
3 min read
More topics on Django
Handling Ajax request in DjangoAJAX (Asynchronous JavaScript and XML) is a web development technique that allows a web page to communicate with the server without reloading the entire page. In Django, AJAX is commonly used to enhance user experience by sending and receiving data in the background using JavaScript (or libraries li
3 min read
User Groups with Custom Permissions in Django - PythonOur task is to design the backend efficiently following the DRY (Don't Repeat Yourself) principle, by grouping users and assigning permissions accordingly. Users inherit the permissions of their groups.Let's consider a trip booking service, how they work with different plans and packages. There is a
4 min read
Django Admin Interface - PythonPrerequisites: Django Introduction and Installation Creating a ProjectThe Django Admin Interface is one of the most powerful features of the Django framework. It provides a ready-to-use interface for managing project data through models, allowing developers and site administrators to perform Create,
3 min read
Extending and customizing django-allauth in PythonDjango-allauth is a powerful Django package that simplifies user authentication, registration, account management, and integration with social platforms like Google, Facebook, etc. It builds on Djangoâs built-in authentication system, providing a full suite of ready-to-use views and forms.Prerequisi
4 min read
Django - Dealing with Unapplied Migration WarningsDjango is a powerful web framework that provides a clean, reusable architecture to build robust applications quickly. It embraces the DRY (Don't Repeat Yourself) principle, allowing developers to write minimal, efficient code.Create and setup a Django project:Prerequisite: Django - Creating projectA
2 min read
Sessions framework using django - PythonDjango sessions let us store data for each user across different pages, even if theyâre not logged in. The data is saved on the server and a small cookie (sessionid) is used to keep track of the user.A session stores information about a site visitor for the duration of their visit (and optionally be
3 min read
Django Sign Up and login with confirmation Email | PythonDjango provides a built-in authentication system that handles users, login, logout, and registration. In this article, we will implement a user registration and login system with email confirmation using Django and django-crispy-forms for elegant form rendering.Install crispy forms using the termina
7 min read