In this lesson, we will explore how to define models and interact with databases in Django. Models are a fundamental part of Django's architecture, allowing you to define the structure of your data and how it interacts with the database.
In Django, a model is a Python class that represents a table in your database. Each attribute of the class represents a field in the table. Django provides a powerful Object-Relational Mapping (ORM) system that allows you to interact with the database using Python code instead of SQL.
To define a model, you need to create a class that inherits from django.db.models.Model. Here’s an example of a simple model for a blog post:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
In this example:
- title is a character field that can hold up to 200 characters.
- content is a text field for the blog post content.
- created_at is a date-time field that automatically sets to the current date and time when a new post is created.
Once you have defined your models, you need to create and apply migrations to create the corresponding tables in the database. Here’s how to do it:
Create migrations: Run the following command in your terminal:
bash
python manage.py makemigrations
This command generates migration files based on the models you defined.
Apply migrations: Run the following command:
bash
python manage.py migrate
This command applies the migrations and creates the tables in the database.
Django's ORM allows you to perform CRUD (Create, Read, Update, Delete) operations easily. Here are some examples:
from myapp.models import Post
# Create a new post
new_post = Post(title='My First Post', content='This is the content of my first post.')
new_post.save()
# Get all posts
all_posts = Post.objects.all()
# Get a single post by ID
single_post = Post.objects.get(id=1)
# Update a post
single_post.title = 'Updated Title'
single_post.save()
# Delete a post
single_post.delete()
Note: Always use
get()carefully, as it raises an exception if the object does not exist. Usefilter()if you are unsure.Note: Remember to run
makemigrationsandmigrateevery time you change your models.
django.db.models.Model.By understanding models and how to interact with databases in Django, you can effectively manage your application's data structure and operations.
Comment with fields for author, email, and text. Run migrations to create the table.get().