文章分类
| 189 | |
| 190 | |
| 191 | class Category(BaseModel): |
| 192 | """文章分类""" |
| 193 | name = models.CharField(_('category name'), max_length=30, unique=True) |
| 194 | parent_category = models.ForeignKey( |
| 195 | 'self', |
| 196 | verbose_name=_('parent category'), |
| 197 | blank=True, |
| 198 | null=True, |
| 199 | on_delete=models.CASCADE) |
| 200 | slug = models.SlugField(default='no-slug', max_length=60, blank=True) |
| 201 | index = models.IntegerField(default=0, verbose_name=_('index')) |
| 202 | |
| 203 | class Meta: |
| 204 | ordering = ['-index'] |
| 205 | verbose_name = _('category') |
| 206 | verbose_name_plural = verbose_name |
| 207 | |
| 208 | def get_absolute_url(self): |
| 209 | return reverse( |
| 210 | 'blog:category_detail', kwargs={ |
| 211 | 'category_name': self.slug}) |
| 212 | |
| 213 | def __str__(self): |
| 214 | return self.name |
| 215 | |
| 216 | @cache_decorator(CacheTimeout.HOUR_10) |
| 217 | def get_category_tree(self): |
| 218 | """ |
| 219 | 递归获得分类目录的父级 |
| 220 | :return: |
| 221 | """ |
| 222 | categorys = [] |
| 223 | |
| 224 | def parse(category): |
| 225 | categorys.append(category) |
| 226 | if category.parent_category: |
| 227 | parse(category.parent_category) |
| 228 | |
| 229 | parse(self) |
| 230 | return categorys |
| 231 | |
| 232 | @cache_decorator(CacheTimeout.HOUR_10) |
| 233 | def get_sub_categorys(self): |
| 234 | """ |
| 235 | 获得当前分类目录所有子集 |
| 236 | :return: |
| 237 | """ |
| 238 | categorys = [] |
| 239 | all_categorys = Category.objects.all() |
| 240 | |
| 241 | def parse(category): |
| 242 | if category not in categorys: |
| 243 | categorys.append(category) |
| 244 | childs = all_categorys.filter(parent_category=category) |
| 245 | for child in childs: |
| 246 | if category not in categorys: |
| 247 | categorys.append(child) |
| 248 | parse(child) |
no outgoing calls