Django ORM 常用增刪改查語法、API及示例
Django ORM 常用增刪改查語法、API及示例
Django ORM(Object-Relational Mapping)是Django框架中用于与数据库进行交互的模块。它提供了一种面向对象的方式来操作数据库,使得开发者可以更加方便地进行增删改查等操作。本文将详细介绍Django ORM的常用增删改查操作及其API,并给出详细的示例和注释。
1. 模型定义 (Models)
首先,我们需要定义一个模型类,该类继承自django.db.models.Model
。模型类中的每个属性都对应数据库中的一个字段。
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
published_date = models.DateField()
isbn = models.CharField(max_length=13)
def __str__(self):
return self.title
2. 序列化器 (Serializers)
为了将模型实例转换为JSON格式的数据,我们通常使用Django REST framework提供的序列化器。
from rest_framework import serializers
from .models import Author, Book
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = '__all__'
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
3. 增 (Create)
3.1 创建单个对象
# 创建一个新作者
new_author = Author(name='John Doe', age=45)
new_author.save()
3.2 使用序列化器创建对象
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
import io
data = {'name': 'Jane Doe', 'age': 30}
serializer = AuthorSerializer(data=data)
if serializer.is_valid():
serializer.save()
4. 查 (Read)
4.1 查询所有对象
authors = Author.objects.all()
for author in authors:
print(author.name, author.age)
4.2 查询单个对象
try:
author = Author.objects.get(id=1)
print(author.name, author.age)
except Author.DoesNotExist:
print("Author not found")
4.3 使用序列化器查询对象
author = Author.objects.get(id=1)
serializer = AuthorSerializer(author)
json_data = JSONRenderer().render(serializer.data)
print(json_data)
5. 改 (Update)
5.1 更新单个字段
author = Author.objects.get(id=1)
author.age = 46
author.save()
5.2 更新多个字段
author = Author.objects.get(id=1)
author.name = 'John Smith'
author.age = 47
author.save()
5.3 使用序列化器更新对象
data = {'name': 'John Smith', 'age': 48}
author = Author.objects.get(id=1)
serializer = AuthorSerializer(author, data=data)
if serializer.is_valid():
serializer.save()
6. 删 (Delete)
6.1 删除单个对象
author = Author.objects.get(id=1)
author.delete()
6.2 批量删除对象
Author.objects.filter(age__lt=30).delete()
7. 高级查询 (Advanced Queries)
7.1 过滤查询 (Filtering)
# 获取年龄大于40的作者
older_authors = Author.objects.filter(age__gt=40)
for author in older_authors:
print(author.name, author.age)
7.2 排序查询 (Ordering)
# 按年龄升序排列作者
authors_sorted_by_age = Author.objects.order_by('age')
for author in authors_sorted_by_age:
print(author.name, author.age)
7.3 聚合查询 (Aggregation)
from django.db.models import Avg, Max, Min, Count, Sum
# 计算平均年龄
average_age = Author.objects.aggregate(Avg('age'))['age__avg']
print(f"Average Age: {average_age}")
7.4 关联查询 (Related Lookups)
# 获取某本书的作者信息
book = Book.objects.get(id=1)
author_name = book.author.name
print(f"The author of the book is: {author_name}")
8. API视图 (API Views)
Django REST framework提供了一些通用的视图来处理常见的HTTP请求。以下是一个简单的例子,展示如何使用这些视图。
8.1 安装Django REST framework
首先,确保你已经安装了Django REST framework:
pip install djangorestframework
8.2 配置settings.py
在settings.py
中添加rest_framework
到INSTALLED_APPS
:
INSTALLED_APPS = [
...,
'rest_framework',
]
8.3 创建视图 (Views)
在views.py
中创建视图:
from rest_framework import viewsets
from .models import Author, Book
from .serializers import AuthorSerializer, BookSerializer
class AuthorViewSet(viewsets.ModelViewSet):
queryset = Author.objects.all()
serializer_class = AuthorSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
8.4 配置URL路由 (URL Routing)
在urls.py
中配置路由:
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import AuthorViewSet, BookViewSet
router = DefaultRouter()
router.register(r'authors', AuthorViewSet)
router.register(r'books', BookViewSet)
urlpatterns = [
path('', include(router.urls)),
]
9. 总结
本文详细介绍了Django ORM的常用增删改查操作及其API,并通过示例展示了如何定义模型、序列化器以及如何使用视图和路由来处理HTTP请求。通过这些内容,你可以更好地理解和使用Django ORM来进行数据库操作。
END