Django Models and Databases
In this tutorial, you will learn how to define models, work with databases, and perform CRUD operations in Django.
Step 1: Defining Models
Models are defined in the `models.py` file of your app. Here is an example of a simple model:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
published_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Step 2: Making Migrations
After defining your models, you need to create migrations to apply the changes to the database:
python manage.py makemigrations
python manage.py migrate
Step 3: Performing CRUD Operations
With your models defined and migrated, you can now perform CRUD operations. Here are some examples:
Create
article = Article.objects.create(title="My First Article", content="This is the content of my first article.")
Read
articles = Article.objects.all()
Update
article = Article.objects.get(id=1)
article.title = "Updated Title"
article.save()
Delete
article = Article.objects.get(id=1)
article.delete()
Follow the Django documentation to learn more about working with models and databases.