Django Models

👋 Hi there, I am Nirmal. I am a former software engineer with a keen interest in data science and analytics domains. Besides, I love to contribute to open source and help others to understand various tech stuffs.
Search for a command to run...

👋 Hi there, I am Nirmal. I am a former software engineer with a keen interest in data science and analytics domains. Besides, I love to contribute to open source and help others to understand various tech stuffs.
No comments yet. Be the first to comment.
This series will cover the core concepts on web application development using Django, from basic installation to user authentications and some core concepts.
In the expansive fields of web development frameworks, Django stands out as a powerful and favored option for creating robust web applications. As an open-source Python web framework, Django was specifically designed to simplify the web development p...
Bias in Machine Learning Bias refers to the simplifying assumptions made by a model to make the target function easier to learn. High bias can lead to underfitting Represents the error introduced by approximating a real-world problem Example: A li...
When it comes to developing software applications, choosing the appropriate architectural style is a critical decision. Among the popular options are microservices and monolithic architecture. By understanding the trade-offs, readers can make well-i...

In a world where information is everywhere, businesses have tons of data at their fingertips. This data is like a goldmine waiting to be used for smart decisions. That's where Big Data analytics and Data Science come in. They're like the experts who ...

Python is a powerful tool for data professionals, largely due to its extensive collection of open-source libraries and packages. In this blog, we'll explore the fundamentals of pandas, with a special focus on its core data structures: Series and Data...

NumPy is a powerful library for numerical computing in Python, offering robust support for large, multi-dimensional arrays and an extensive collection of mathematical functions. Creating Arrays To begin using NumPy, import the library and create arra...

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 |
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',
}
}
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
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.
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
| 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. |