Django Fundamentals for Python Developers
Django Models
Models as Blueprints
In Django, a model is the single, definitive source of information about your data. Think of it as a blueprint for a database table, but written in Python. Instead of writing complex SQL, you define the structure of your data as a Python class.
This is possible because of Django's Object-Relational Mapper, or ORM. The ORM is a powerful feature that acts as a translator. It converts the Python model classes you write into the SQL commands needed to create, read, update, and delete data in your database. This lets you work with your database using simple, intuitive Python code.
By enabling developers to deal with database models using Python code rather than SQL queries, Django's Object-Relational Mapping (ORM) streamlines database interactions.
Defining a Simple Model
Let's define a model for a simple blog post. We'll create a Python class that inherits from django.db.models.Model. Inside this class, we define the fields of our model as class attributes. Each attribute maps to a database column.
from django.db import models
class BlogPost(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
pub_date = models.DateTimeField('date published')
Here’s a breakdown of what's happening:
title: This is aCharField, which is used for small strings. You must specify amax_length.content: This is aTextField, which is for large blocks of text. You don't need to set a length limit.pub_date: This is aDateTimeField, which stores a date and a time.
Django has a wide variety of field types to represent different kinds of data, from numbers (IntegerField, FloatField) to booleans (BooleanField).
Connecting Models Together
Real applications rarely have data that exists in isolation. Data is connected. For instance, a blog post has an author, and it might have several tags. Django models handle these relationships with three types of fields: ForeignKey, ManyToManyField, and OneToOneField.
A ForeignKey field creates a many-to-one relationship. For example, a blog post is written by one author, but an author can write many blog posts.
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class BlogPost(models.Model):
# ... other fields
author = models.ForeignKey(Author, on_delete=models.CASCADE)
# The on_delete=models.CASCADE tells Django that if an
# Author is deleted, all their BlogPosts should be deleted too.
A ManyToManyField sets up a many-to-many link. A blog post can have multiple tags, and a single tag can be applied to many different posts.
from django.db import models
class Tag(models.Model):
name = models.CharField(max_length=50)
class BlogPost(models.Model):
# ... other fields
tags = models.ManyToManyField(Tag)
Finally, a OneToOneField is like a ForeignKey, but it ensures that a record in one table can only be linked to a single record in another. It's often used for things like extending the built-in user model with a user profile.
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(blank=True)
location = models.CharField(max_length=100, blank=True)
Applying Your Changes
After you define or change your models, you need to tell the database about it. This is where migrations come in. Migrations are Django's way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema.
It's a two-step process that you run from your terminal.
First, you run
python manage.py makemigrations. This command inspects your models and creates new migration files based on the changes you've made since the last migration.
Second, you run
python manage.py migrate. This command takes the migration files that haven't been applied yet and runs them against your database, updating the schema to match your models.
Always use Django's built-in migration system to handle database changes.
This system is powerful because it's version-controlled. Each migration file is a step-by-step record of your database changes, which is incredibly helpful when working on a team or deploying your application.
What is the primary function of a Django model?
The system in Django that translates Python model classes into database query language (like SQL) is known as the:
Models are the foundation of any Django application. By defining them clearly and understanding how they relate to each other, you're setting yourself up to build powerful, data-driven websites.