Django Tutorial: Defining Models

beginner
16 min

Django Tutorial: Defining Models

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!

Understanding Models

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.

Creating Our First Model

Let's create a simple model for a blog post. Open your myblog app's models.py file, and add the following code:

python
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:

  1. CharField: Used for short strings like titles.
  2. TextField: Used for longer text like blog content.
  3. 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.

Migrating the Model

Now that we've defined our model, we need to create the corresponding database table. Run the following command in your terminal:

bash
python manage.py makemigrations python manage.py migrate

These commands create a migration file and apply it to the database, creating the table.

Creating a Blog Post

To create a blog post, we'll use the Django shell. Run:

bash
python manage.py shell

Then, create a new blog post:

python
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()

Quiz

Quick Quiz
Question 1 of 1

What is the primary purpose of a Django model?

Stay tuned for the next lesson, where we'll learn how to query our models! πŸš€