Django models are Python classes that define the structure of your database tables. Each class corresponds to a table, and each attribute within the class represents a column in the table. Models are central to Django's Object-Relational Mapping (ORM), which lets you interact with the database using Python code instead of SQL queries.
To create a model in Django, you define a Python class that inherits from django.db.models.Model. Here's a simple example of a model representing a blog post:
from django.db import models
class BlogPost(models.Model):
title = models.CharField(max_length=200) # A short text field
content = models.TextField() ###### A long text field
published_at = models.DateTimeField(auto_now_add=True) ###### Stores the date and time when the record is created
author = models.CharField(max_length=100) # Name of the author
In this example
After defining your models, you need to create and apply migrations to reflect the changes in the database. Migrations are Django's way of managing database schema changes.
Here's how you do it:
# Create migrations
python manage.py makemigrations
# Apply migrations
python manage.py migrate
Once you've defined your models and applied migrations, you can use Django's ORM to create, retrieve, update, and delete records.
Creating Records
To create a new record, you can instantiate the model and call the save() method:
# Create a new blog post
post = BlogPost(title="My First Post", content="This is my first blog post.", author="John Doe")
post.save() # Saves the record to the database
Retrieving Records
To retrieve records, you can use Django's query methods like all(), filter(), and get():
# Get all blog posts
all_posts = BlogPost.objects.all()
# Get blog posts by a specific