用 Get 方法实现文章分类功能
1. 思路
2. Model层
class article(models.Model):
title = models.CharField(null=True, blank=True,
max_length=200)
context = models.TextField(null=True, blank=True)
# 'Tech'后台管理界面的选择名称
# 'tech'前端页面传递过来的具体的值,?tag=tech
TAG_CHOICES = (
('tech', 'Tech'),
('life', 'Life'),
)
tag = models.CharField(
null=True, blank=True,
# choices提供一个下拉选择,是一个元组结构
max_length=200,choices=TAG_CHOICES)
def __str__(self):
return self.title
2.1 合并、运行数据库
python3 manage.py makemigrations
python3 manage.py migrate
# 不要忘记这个日常操作
3. View层
def index_html(request):
# 得到 ?tag=xxx 中的xxx的值
queryset = request.GET.get('tag')
# queryset不为空时,即有参访问, filter过滤器,会提取出符合的信息
if queryset:
article_list = article.objects.filter(tag=queryset)
# 无参访问
else:
article_list = article.objects.all()
context = {
'article': article_list
}
return render(request, 'index.html', context)