Django Tutorial: Models Introduction πŸš€

beginner
8 min

Django Tutorial: Models Introduction πŸš€

Welcome back to CodeYourCraft! Today, we're diving into the heart of Django – Models. If you're new to Django, don't worry! We'll explain everything from scratch. 🎯

What are Django Models? πŸ€”

In simple terms, a Model in Django is a blueprint for a database table. It defines the structure, data types, and relationships of the data stored in the database. πŸ“

Why Models are important? πŸ’‘

  1. They handle the tedious task of interacting with the database, allowing us to focus on building our application.
  2. Models provide a clean and consistent way to represent data in our Django project.

Creating a Simple Model πŸ”§

Let's create a simple model for a BlogPost:

python
from django.db import models class BlogPost(models.Model): title = models.CharField(max_length=200) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True)

πŸ“ Note:

  1. models.CharField is used for short text fields like titles.
  2. models.TextField is used for longer text fields like content.
  3. models.DateTimeField records the creation date of the object.
  4. auto_now_add=True means the field is automatically filled with the current date and time when the object is created.

Saving Data to the Database πŸ“„

Now that we have our BlogPost model, let's see how to save data to the database:

python
from django.utils import timezone from .models import BlogPost def create_blog_post(title, content): blog_post = BlogPost(title=title, content=content, published_at=timezone.now()) blog_post.save() return blog_post

Here, we've created a function create_blog_post that accepts a title and content, creates a new BlogPost object, and saves it to the database.

Querying Models πŸ”

To query data from the database, we can use Django's powerful QuerySet API:

python
from .models import BlogPost blog_posts = BlogPost.objects.all()

This will fetch all the BlogPost objects from the database.

Quiz 🌟

Quick Quiz
Question 1 of 1

What is the purpose of a Model in Django?


Remember, practice is key to mastering Django. Keep coding and experimenting with Models. In the next lesson, we'll dive deeper into working with Models, including creating relationships between them.

See you there! πŸŽ‰