
利用model中的save方法,变相的实现递归循环,所有子分类都能在其中更新,感觉挺巧妙,之前的实现方式确实太烂了。 order的方法竟然支持1:23:2 这种方式的排序,轻松解决以前靠order_id排序的弊端。精简了代码。
其中一断代码: 利用reverse 方法反推url,与无限级的order 还能用在自动生成类别链接上,便捷灵活。
1
2 3 4 5 6 7 |
def htmlpath ( self ): paths c url paths. |
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
from django.
db. models. signals import pre_save class ArticleCategory name parent path
indent_num indent node node ordering childrens children. children. #信号触发,更新 def inital_articlecategory_path instance. instance. pre_save. |
admin.py
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class ArticleCategoryAdmin
(admin. ModelAdmin ): list_display ordering patha. patha.
indent_num p treenode. treenode. admin. |
分析代码后,发现该方法可以不使用signals 来实现,在path变换后 再次运行 super(ArticleCategory,self).save(*args, ** kwargs) ,这样在children中才能在新的循环save中更新path时变更正确,否则path保存时会异常。
这个是不使用signals的代码,依靠model的save的实现。
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
class ArticleCategory
(models. Model ): name parent path
indent_num indent node node ordering childrens
children. children. |