Welcome back to CodeYourCraft! Today, we're diving deep into one of Django's most powerful features - Defining Models. Models are the backbone of any Django application, enabling us to structure and manage data. Let's get started!
A Django model is a Python class that defines a database schema for a specific set of data. It serves as an interface between the database and the rest of the application.
π‘ Pro Tip: Think of models as blueprints for creating database tables.
Let's create a simple model for a blog post. Open your myblog app's models.py file, and add the following code:
from django.db import models
class BlogPost(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
publish_date = models.DateTimeField('date published')
def __str__(self):
return self.titleπ Note: Each field in the model corresponds to a column in the database table.
Here's what each field type does:
CharField: Used for short strings like titles.TextField: Used for longer text like blog content.DateTimeField: Used for date and time.π― Key Insight: The __str__ method is crucial. It allows Django to display a user-friendly string for each instance when we list them.
Now that we've defined our model, we need to create the corresponding database table. Run the following command in your terminal:
python manage.py makemigrations
python manage.py migrateThese commands create a migration file and apply it to the database, creating the table.
To create a blog post, we'll use the Django shell. Run:
python manage.py shellThen, create a new blog post:
from myblog.models import BlogPost
blog_post = BlogPost(title='Welcome to My Blog', content='This is my first post!', publish_date=datetime.now())
blog_post.save()What is the primary purpose of a Django model?
Stay tuned for the next lesson, where we'll learn how to query our models! π