Django models are one of the essential tools of this web framework that are used in the field of server-side programming, which are responsible for managing data in a structured and manageable way. Models can convert complex database tables into simple Python classes, allowing developers to work with their SQL code directly.
One interesting feature of Django models is the ability to define them in a way that creates their own database table as Python classes, managing all their attributes and behaviors through these classes.
Another attractive aspect is the ability to quickly apply changes that are made to models in the database. By utilizing the migration system in Django, every change made in the models can automatically trigger the necessary actions to alter the database.
Now that we understand how models relate to the development of web applications with Django, let's look at a sample code:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
publication_date = models.DateField()
def __str__(self):
return self.title
In this code, we see how a simple model for articles is created.
from django.db import models
In this line, we import the
models
module from Django, which includes the various model types needed.class Article(models.Model):
In this line, we define our model class which inherits from
models.Model
, meaning this model will be a Django model.title = models.CharField(max_length=200)
We add an attribute
title
which is a type of data CharField
with a maximum length of 200 characters.content = models.TextField()
We have an attribute
content
which is of type TextField
used for storing longer textual content.publication_date = models.DateField()
Here, we have an attribute
publication_date
that stores the publication date of the article and is of type DateField
.def __str__(self):
This method returns a string representation of the object, which in this case is the article's title.