Django models are used to define the structure of the data that will be stored in the database. They provide a way to interact with the database using Python, making it easy to perform CRUD (create, read, update, and delete) operations without writing raw SQL queries. In this article, we will discuss the basics of Django models and how to use them to work with a database.
A model in Django is a Python class that inherits from the django.db.models.Model class. Each model class defines a set of fields that correspond to the columns in a database table. For example, the following code defines a model called "Person" with two fields, "first_name" and "last_name", that correspond to the "first_name" and "last_name" columns in the "person" table:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
Here, We defined a model Person
which has two fields first_name
and last_name
which are of type CharField and have max_length of 30 characters. There are various other fields available in Django such as IntegerField, DateField, BooleanField, etc. which you can use based on your needs.
Django provides several different field types, such as CharField, TextField, IntegerField, DateField, and so on. These field types are used to define the types of data that will be stored in the database. For example, a CharField is used to store short text strings, while a TextField is used to store longer text strings.
In addition to the fields, a Django model also has a few additional methods that are provided by the Model base class. The save()
method is used to save a new model instance to the database or update an existing instance. And objects
attribute, a default manager for the model, provides various useful methods for querying the database such as filter()
, exclude()
, all()
, first()
, last()
, get()
, create()
, update()
, etc.
person = Person.objects.create(first_name='John', last_name='Doe')
# Update the person
person.first_name = 'Jane'
person.save()
# Delete the person
person.delete()
Once you have defined your models, you need to create the corresponding database tables. This is done using the makemigrations
and migrate
management commands. The makemigrations
command creates migration files, which are used to keep track of changes to your models over time. The migrate
command creates the actual database tables and applies any pending migrations.
In conclusion, Django models provide an easy and intuitive way to work with databases in a Python web application. They allow you to define the structure of your data using Python classes and provide a convenient way to interact with the database using methods such as save(), filter() and so on. Understanding how to use models is essential to building a Django application.