download:Go+Python 双语言混合开发 盯紧技术先机 放松高薪时机
from django. db. models. signals import pre_save
class ArticleCategory (models. Model):
name = models. CharField (max_length = 50)
parent = models. ForeignKey ('self' , null = True , blank = True , related_name = 'children')
path = models. CharField (max_length = 255 , null = True , blank = True)
def __unicode__ (self):
if self. id == self. path:
return self. name
else:
return self. node
def _node (self):
indent_num = len (self. path. split ( ':') ) - 1
indent = '....' * indent_num
node = u '%s%s' % (indent , self. name)
return node
node = property (_node)
class Meta:
ordering = ['path']
#设置在 model 中的用处是,是在所有节点保留时递归的循环上来,更新所有的节点的门路
def save (self , * args , ** kwargs):
super (ArticleCategory , self). save (*args , ** kwargs)
if self. parent:
self. path = '%s:%s' % (self. parent. path , self. id)
else:
self. path = self. id
childrens = self. children. all ( )
if len (childrens) > 0:
for children in childrens:
children. path = '%s:%s' % (self. path , children. id)
children. save ( )
super (ArticleCategory , self). save (*args , ** kwargs)
信号触发,更新
def inital_articlecategory_path (sender , instance , **kwargs):
if instance. id:
if instance. parent:
instance. path = '%s:%s' % (instance. parent. path , instance. id)
else:
instance. path = instance. id
pre_save. connect (inital_articlecategory_path , sender =ArticleCategory)
class ArticleCategoryAdmin (admin. ModelAdmin):
list_display = ['treenode' , 'patha' , 'id' ,]
ordering = ['path']
def patha (self , obj):
if obj. parent:
return u '%s > %s' % (obj. parent , obj. name)
return obj. name
patha. short_description = 'path'
patha. allow_tags = True
def treenode (self , obj):
indent_num = len (obj. path. split ( ':') ) - 1
p = '<div style="text-indent:%spx;">%s</div>' % (indent_num* 25 , obj. name)
return p
treenode. short_description = 'tree path'
treenode. allow_tags = True
admin. site. register (ArticleCategory , ArticleCategoryAdmin)