尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

HoRain云--Django 5 实战:ORM、DRF、权限与性能优化

HoRain云--Django 5 实战:ORM、DRF、权限与性能优化 1. 创建项目bash复制下载pip install django djangorestframework django-admin startproject mysite cd mysite python manage.py startapp api2. 模型设计python复制下载from django.db import models class Category(models.Model): name models.CharField(max_length100) class Article(models.Model): title models.CharField(max_length200) content models.TextField() category models.ForeignKey(Category, on_deletemodels.CASCADE, related_namearticles) created_at models.DateTimeField(auto_now_addTrue)3. ORM 查询优化select_related一对一/外键prefetch_related多对多/反向外键python复制下载articles Article.objects.select_related(category).all()避免 N1 查询。4. DRF 序列化器python复制下载from rest_framework import serializers class ArticleSerializer(serializers.ModelSerializer): category_name serializers.CharField(sourcecategory.name, read_onlyTrue) class Meta: model Article fields [id, title, content, category, category_name, created_at]5. 视图与路由python复制下载from rest_framework import viewsets from .models import Article from .serializers import ArticleSerializer class ArticleViewSet(viewsets.ModelViewSet): queryset Article.objects.select_related(category).all() serializer_class ArticleSerializer路由python复制下载from rest_framework.routers import DefaultRouter router DefaultRouter() router.register(articles, ArticleViewSet) urlpatterns router.urls6. 认证与权限python复制下载from rest_framework.permissions import IsAuthenticatedOrReadOnly class ArticleViewSet(viewsets.ModelViewSet): permission_classes [IsAuthenticatedOrReadOnly]JWT 认证bash复制下载pip install djangorestframework-simplejwt7. 分页与过滤python复制下载REST_FRAMEWORK { DEFAULT_PAGINATION_CLASS: rest_framework.pagination.PageNumberPagination, PAGE_SIZE: 20, DEFAULT_FILTER_BACKENDS: [django_filters.rest_framework.DjangoFilterBackend], }8. 缓存python复制下载from django.core.cache import cache def get_articles(): data cache.get(articles) if not data: data list(Article.objects.all().values()) cache.set(articles, data, 60) return data生产环境使用 Redis。9. 性能优化使用only()、defer()减少字段。使用bulk_create批量插入。数据库索引db_indexTrue。使用django-debug-toolbar分析 SQL。10. 部署bash复制下载pip install gunicorn gunicorn mysite.wsgi:application --bind 0.0.0.0:8000 --workers 4Nginx 反向代理静态文件交给 Nginx。11. 常见坑DEBUGTrue 上生产。忘记ALLOWED_HOSTS。迁移文件冲突。循环导入。12. 总结Django 5 DRF 能快速构建规范 REST API。重点掌握 ORM 优化、权限和缓存才能支撑高并发场景。
返回列表