How is the ORM framework used in Django?
The ORM (Object-Relational Mapping) in Django is a framework for interacting with databases, offering a way to manage databases in an object-oriented manner instead of directly using SQL statements.
You can use the ORM framework in Django to describe the table structure in the database by defining model classes, and then manipulate these model objects to perform CRUD operations on the database. Here is how you can use the ORM framework in Django:
- a model from the django.db.models package
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
- Database migration: Once the models are defined, you can use Django’s database migration tool to create database tables or update table structures.
$ python manage.py makemigrations # 生成迁移文件
$ python manage.py migrate # 执行迁移
- Database operations are performed through objects of model classes, such as creating, deleting, updating, and querying.
# 创建对象
user = User(name="Alice", age=25)
user.save()
# 查询对象
users = User.objects.all()
user = User.objects.get(name="Alice")
# 更新对象
user.name = "Bob"
user.save()
# 删除对象
user.delete()
- Query filtering: Django’s ORM framework offers a wide range of filtering methods, allowing users to filter query results based on specified conditions.
# 等值查询
users = User.objects.filter(age=25)
# 模糊查询
users = User.objects.filter(name__contains="ob")
# 范围查询
users = User.objects.filter(age__gt=20, age__lt=30)
# 排序
users = User.objects.order_by("-age")
# 限制查询结果数量
users = User.objects.all()[:10]
- Django’s ORM framework supports various types of association relationships, such as one-to-one, one-to-many, and many-to-many. Relationships can be established by defining association fields between model classes and performing operations using related methods.
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(User, on_delete=models.CASCADE)
# 查询某个作者的所有文章
articles = Article.objects.filter(author=user)
# 查询某篇文章的作者
author = article.author
# 创建关联对象
article = Article(title="Title", author=user)
article.save()
With the brief introduction above, you can now start using Django’s ORM framework to manipulate databases. Of course, Django’s ORM framework also has more advanced features and functionalities, such as aggregation, join queries, etc. You can refer to the official Django documentation for a deeper understanding.