原来我们的模型是有些简陋的,这一讲我们将文章模型拓展一下。

安装插件

首先,我们安装一个为方便复杂序列化的插件:

1
pip3 install drf-flex-fields

拓展模型

首先,我们在顶部引入django的User模型:

1
2
3
# backend/blog/models.py

from django.contrib.auth.models import User # 顶部新增

接着,新增标签栏目两个拓展模型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# backend/blog/models.py

class Column(models.Model): # Column类,栏目
name = models.CharField(max_length=50, unique=True) # 短字段,最多50字,unique代表唯一

class Meta: # 内部类
verbose_name = "栏目 Column"

def __str__(self): # 后台返回内容
return self.name


class Tag(models.Model): # 同上,不在阐述
name = models.CharField(max_length=100, unique=True)

class Meta:
verbose_name = "标签 Tag"

def __str__(self):
return self.name

这两个模型是Article模型的外键,接下来拓展Article模型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# backend/blog/models.py

class Article(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
title = models.CharField(max_length=50)
body = models.TextField()
main = models.CharField(max_length=10000,blank=True)
column = models.ForeignKey( # 栏目外键,新增
Column,
related_name='articles',
on_delete=models.CASCADE,
blank=True,
null=True
)
tags = models.ManyToManyField(Tag, blank=True) # 标签外键,新增
views = models.PositiveIntegerField(default=0, editable=False) # 浏览量,新增
course = models.CharField(max_length=500, blank=True) # 属于某课程,新增
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

class Meta:
ordering = ('-created',)
verbose_name = "文章 Article"

def __str__(self):
return self.title

模型修改完后记得迁移,否则不会生效

1
2
python manage.py makemigrations
python manage.py migrate

拓展序列化器

这里不是特别重要,都写在注释里了,将整个文件都贴出来:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# backend/blog/serialiezer.py

from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Article
from rest_flex_fields import FlexFieldsModelSerializer # 文章开头安装的

class ArticleSerializer(FlexFieldsModelSerializer): # 继承要修改
author = serializers.ReadOnlyField(source='author.username') # 作者
column = serializers.StringRelatedField() # 栏目
tags = serializers.StringRelatedField(many=True) # 标签

class Meta:
model = Article
# 这个有简便写法,博主保险起见就这么写,感兴趣的读者可以自行查阅
fields = ['id', 'author', 'column', 'tags', 'course', 'title', 'body', 'main', 'views', 'created', 'updated']

修改视图

视图这里只需要在文章详情的地方改就行了,代码全贴出来:

1
2
3
4
5
6
7
8
9
10
11
12
# backend/blog/views.py

from rest_framework import viewsets, mixins
from .serializer import ArticleSerializer
from .models import Article

class ArticleViewSet(mixins.ListModelMixin, # 列表
mixins.RetrieveModelMixin, # 详情
viewsets.GenericViewSet # 杂散的其他类
):
queryset = Article.objects.all()
serializer_class = ArticleSerializer

后台美化

首先,我们装一下美化用的simpleui

1
pip3 install django-simpleui

接着,在settings.py里面修改:

1
2
3
4
5
6
7
8
9
10
11
12
# backend/backend/settings.py

INSTALLED_APPS = [
'simpleui',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'blog'

完成后,重启项目,就会发现后台变漂亮啦

注册到后台

之前应该是漏讲了一个地方,没有把模型注册到后台,所以我们在admin.py中添加:

1
2
3
4
5
6
# backend/blog/admin.py

from .models import Article, Column, Tag
admin.site.register(Article)
admin.site.register(Column)
admin.site.register(Tag)

然后就可以在后台写文章啦!

有任何疑问欢迎加QQ群:Python学习交流 1140464262