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. π―
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. π
Let's create a simple model for a BlogPost:
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:
models.CharField is used for short text fields like titles.models.TextField is used for longer text fields like content.models.DateTimeField records the creation date of the object.auto_now_add=True means the field is automatically filled with the current date and time when the object is created.Now that we have our BlogPost model, let's see how to save data to the database:
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_postHere, 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.
To query data from the database, we can use Django's powerful QuerySet API:
from .models import BlogPost
blog_posts = BlogPost.objects.all()This will fetch all the BlogPost objects from the database.
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! π