You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
from django . contrib . auth import get_user_model
from django . contrib . auth . hashers import make_password
from django . core . management . base import BaseCommand
from blog . models import Article , Tag , Category
class Command ( BaseCommand ) :
"""
mk:
Django管理命令类, 用于创建测试数据
该命令会创建测试用户、分类、标签和文章数据,用于开发和测试环境
继承自Django的BaseCommand基类
"""
help = ' create test datas '
def handle ( self , * args , * * options ) :
"""
mk:
处理命令执行的主要逻辑
参数:
*args: 位置参数元组
**options: 命令行选项字典
返回值:
None
"""
# mk:创建或获取测试用户
user = get_user_model ( ) . objects . get_or_create (
email = ' test@test.com ' , username = ' 测试用户 ' , password = make_password ( ' test!q@w#eTYU ' ) ) [ 0 ]
# mk:创建父级分类
pcategory = Category . objects . get_or_create (
name = ' 我是父类目 ' , parent_category = None ) [ 0 ]
# mk:创建子级分类
category = Category . objects . get_or_create (
name = ' 子类目 ' , parent_category = pcategory ) [ 0 ]
category . save ( )
# mk:创建基础标签
basetag = Tag ( )
basetag . name = " 标签 "
basetag . save ( )
# mk:批量创建20篇文章及其对应标签
for i in range ( 1 , 20 ) :
article = Article . objects . get_or_create (
category = category ,
title = ' nice title ' + str ( i ) ,
body = ' nice content ' + str ( i ) ,
author = user ) [ 0 ]
tag = Tag ( )
tag . name = " 标签 " + str ( i )
tag . save ( )
article . tags . add ( tag )
article . tags . add ( basetag )
article . save ( )
#mk: 清除缓存并输出成功信息
from djangoblog . utils import cache
cache . clear ( )
self . stdout . write ( self . style . SUCCESS ( ' created test datas \n ' ) )