原来我们的模型是有些简陋的,这一讲我们将文章模型拓展一下。
安装插件 首先,我们安装一个为方便复杂序列化的插件:
1 pip3 install drf-flex-fields
拓展模型 首先,我们在顶部引入django的User
模型:
1 2 3 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 class Column (models.Model): name = models.CharField(max_length=50 , unique=True ) 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 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 from rest_framework import serializersfrom django.contrib.auth.models import Userfrom .models import Articlefrom 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 from rest_framework import viewsets, mixinsfrom .serializer import ArticleSerializerfrom .models import Articleclass 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 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 from .models import Article, Column, Tagadmin.site.register(Article) admin.site.register(Column) admin.site.register(Tag)
然后就可以在后台写文章啦!
有任何疑问欢迎加QQ群:Python学习交流 1140464262