Django models are a fundamental component of Django web applications, offering a simplified and pythonic way to define the structure of your data. Acting as Python classes, Django models enable seamless interactions with the underlying database. With models, developers can work with data more intuitively, abstracting away the complexities of SQL queries and database management.
Each model is a Python class that
subclasses django.db.models.Model.
Each attribute of the model represents a database field.
Example :
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
def __str__(self):
return self.title
In this example, the "Post" model defines fields for title, description, and image. The CharField
represents a character field with a maximum length of 200 characters, while the TextField
represents a longer text field. The __str__
method returns the title of the post for better readability.
Corresponding schema
Field Name | Data Type | Constraints |
id | AutoField (Primary Key) | Automatically generated and unique |
title | CharField | Maximum length: 200 |
description | TextField |
Databases in Django
In Django, the default database is set up to use SQLite as the database engine.
In your project's "settings.py" file, the default database configuration is typically set up like this:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # SQLite database engine 'NAME': BASE_DIR / 'db.sqlite3', # Database file path } }
Explanation of the configuration:
ENGINE
: This specifies the database engine to be used, which is set to'django.db.backends.sqlite3'
for SQLite.NAME
: This indicates the file path where the SQLite database file will be created and stored.By default, it is set to
'db.sqlite3'
, and it is placed in the project's base directory (BASE_DIR
). You can change the name or location of the SQLite database file by modifying this setting.
When connecting to other databases extra connection parameters will be required, let's take an example of PostgreSQL
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'database_name', 'USER': 'database_user', 'PASSWORD': 'database_password', 'HOST': '127.0.0.1', 'PORT': '5432', } }
Django Migrations
Whenever changes are made to the models in our Django project, we need to execute two commands: makemigrations
and migrate
.
makemigrations
generates SQL commands for both preinstalled apps and newly created app models that are added to the installed apps.
On the other hand, migrate
applies these SQL commands to the database, making the necessary changes.
#create new database migration files
Python manage.py makemigrations
#this create table in the database
Python manage.py migrate
Crud operation from Admin interface
For this , First I need to register my model in admin.py
from django.contrib import admin
from .models import Post
admin.site.register(Post)
After you register this , then you can do CRUD operation from Django admin interface.
While Django's admin interface provides a user-friendly way to interact with data, the Django shell offers a powerful command-line interface to manage your models and database.
Performing various crud operation from shell
To access the Django shell, open your terminal or command prompt, navigate to your Django project directory, and run the following command:
python manage.py shell
This command open shell terminal where you can perform data operations.
Creating Records
>>>> new_post = Post( title = "BitsNotion", description = "Post Description", ) >>> new_post.save()#Save data to database
Reading Records
To retrieve record from
Post
model .We can perform various operations.Retrieve all data
all_posts = Post.objects.all()
Retrieve a specific post by its primary key (id)
post = Post.objects.get(id=1)
Filter posts based on specific criteria (e.g., title)
query_set = Post.objects.filter(title='BitsNotion')
Updating Records
# Retrieve the post you want to update post = Post.objects.get(id=1) post.title = 'Updated Post Title' post.save()
Deleting Records
# Retrieve the post you want to delete post = Post.objects.get(id=1) post.delete()#delete your post
Various model fields list
Field Type | Title | Description |
AutoField | Auto-Incrementing Primary Key | An automatically incrementing field that serves as the primary key for each record. It assigns a unique integer value to each new record automatically. |
BigIntegerField | 64-bit Integer Field | A field that stores large numerical values represented by 64-bit integers. Useful for handling very large numbers. |
BooleanField | True/False Field | A field to represent true/false values or boolean choices. It stores True or False values to indicate binary choices. |
CharField | Character Field | A field for storing short strings with a fixed maximum length. Commonly used for names, titles, or other short pieces of text. |
DateField | Date Field | A field to store dates without the time component. It can represent dates ranging from 1000-01-01 to 9999-12-31. |
DateTimeField | Date and Time Field | A field to store both dates and time with microsecond precision. It represents dates and times ranging from 1000-01-01 to 9999-12-31. |
DecimalField | Decimal Field | A field for storing decimal numbers with fixed-precision. It is useful for handling financial data or other precise numeric values. |
EmailField | Email Address Field | A field to store valid email addresses. It validates input to ensure it follows the correct email format. |
FileField | File Upload Field | A field to upload and store files. It can be used to handle file uploads, such as images, documents, or other files. |
FloatField | Floating-Point Number Field | A field for storing floating-point numbers. It can represent real numbers with decimal fractions, e.g., 3.14. |
ImageField | Image Upload Field | Similar to FileField , but it is specifically used for uploading and storing image files. |
IntegerField | Integer Field | A field for storing whole numbers without any decimal places. It represents 32-bit signed integers. |
TextField | Text Field | A field for storing long text strings with unlimited length. It is useful for storing large pieces of text, such as articles or descriptions. |
URLField | URL Field | A field to store valid URLs. It validates input to ensure it follows the correct URL format. |
UUIDField | Universally Unique Identifier Field | A field to store universally unique identifiers (UUIDs). UUIDs are 128-bit unique identifiers, often used to ensure uniqueness in distributed systems. |