视图和drf简单使用

master
barney 2 years ago
parent 1cefa6ba24
commit d972386123
  1. 3
      article/admin.py
  2. 25
      article/migrations/0001_initial.py
  3. 16
      article/models.py
  4. 19
      article/serializers.py
  5. 9
      article/urls.py
  6. 94
      article/views.py
  7. BIN
      db.sqlite3
  8. 17
      drf_vue_blog/settings.py
  9. 19
      drf_vue_blog/urls.py

@ -1,3 +1,4 @@
from django.contrib import admin
from article.models import Article
# Register your models here.
admin.site.register(Article)

@ -0,0 +1,25 @@
# Generated by Django 3.1.3 on 2022-09-22 10:24
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('body', models.TextField()),
('created', models.DateTimeField(default=django.utils.timezone.now)),
('updated', models.DateTimeField(auto_now=True)),
],
),
]

@ -1,3 +1,17 @@
from django.db import models
from django.utils import timezone
# Create your models here.
# 博客文章 model
class Article(models.Model):
# 标题
title = models.CharField(max_length=100)
# 正文
body = models.TextField()
# 创建时间
created = models.DateTimeField(default=timezone.now)
# 更新时间
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title

@ -0,0 +1,19 @@
from rest_framework import serializers
from article.models import Article
# 返回文章列表或创建一篇文章
class ArticleListSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = [
'id',
'title',
'created',
'body',
]
# 返回文章详情
class ArticleDetailSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = '__all__'

@ -0,0 +1,9 @@
from django.urls import path
from article import views
app_name = 'article'
urlpatterns = [
path('', views.ArticleList.as_view(), name='list'),
path('<int:pk>/', views.ArticleDetail.as_view(), name='detail')
]

@ -1,3 +1,93 @@
from django.shortcuts import render
from article.models import Article
from article.serializers import ArticleListSerializer, ArticleDetailSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
from django.http import Http404
from rest_framework import mixins
from rest_framework import generics
from rest_framework import status
# Create your views here.
@api_view(['GET', 'POST'])
def article_list(request):
# 获取所有文章列表
if request.method == 'GET':
articles = Article.objects.all()
serializer = ArticleListSerializer(articles, many=True)
return Response(serializer.data)
# 创建新的文章
elif request.method == 'POST':
serializer = ArticleListSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# 和article_list()功能相同
class ArticleList(generics.ListCreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleListSerializer
# 第一种版本
# class ArticleDetail(APIView):
# """文章详情视图"""
# def get_object(self, pk):
# """获取单个文章对象"""
# try:
# # pk代表主键
# return Article.objects.get(pk=pk)
# except:
# raise Http404
#
# def get(self, request, pk):
# article = self.get_object(pk)
# serializer = ArticleDetailSerializer(article)
# # 返回Json数据
# return Response(serializer.data)
#
# def put(self, request, pk):
# article = self.get_object(pk)
# serializer = ArticleDetailSerializer(article, data=request.data)
# # 验证提交的数据是否合法
# # 不合法就返回400
# if serializer.is_valid():
# # 序列化器将持有的数据反序列化后
# # 保存到数据库
# serializer.save()
# return Response(serializer.data)
# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#
# def delete(self, request, pk):
# article = self.get_object(pk=pk)
# article.delete()
# # 删除成功后返回204
# return Response(status=status.HTTP_204_NO_CONTENT)
# 第二种版本
# class ArticleDetail(mixins.RetrieveModelMixin,
# mixins.UpdateModelMixin,
# mixins.DestroyModelMixin,
# generics.GenericAPIView):
# """文章详情视图"""
# queryset = Article.objects.all()
# # 序列化类
# serializer_class = ArticleDetailSerializer
#
# def get(self, request, *args, **kwargs):
# return self.retrieve(request, *args, **kwargs)
#
# def put(self, request, *args, **kwargs):
# return self.update(request, *args, **kwargs)
#
# def delete(self, request, *args, **kwargs):
# return self.destroy(request, *args, **kwargs)
# ArticleDetail类还可以简化为下面的代码
class ArticleDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Article.objects.all()
serializer_class = ArticleDetailSerializer

Binary file not shown.

@ -1,15 +1,3 @@
"""
Django settings for drf_vue_blog project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
@ -37,6 +25,7 @@ INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'article',
]
@ -107,13 +96,13 @@ AUTH_PASSWORD_VALIDATORS = [
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)

@ -1,21 +1,8 @@
"""drf_vue_blog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')),
path('api/article/', include('article.urls', namespace='article')),
]

Loading…
Cancel
Save