背景说明:¶
昨天跟客户谈需求时,客户要求做一个数状数据结构,类似于:
不仅要在前台这么显示,后台也要这么显示。¶
一番google之后 ,感谢Stack Overflow让我找到了Django mptt,感谢残阳似血血写了如此华丽的博客,小生很喜欢添加趣点功能
解决方案¶
用django mptt改变数据结构¶
用django-mptt-admin改变数状结构在django后台的显示方式¶
具体操作¶
1. 安装django mptt¶
下载源码 https://github.com/django-mptt/django-mptt
或
pip install django-mptt
2. 配置django mptt¶
在settings文件下的INSTALLED_APPS中添加'mptt'
就这么简单,安装配置结束了
3. 使用django mptt¶
写model,继承MPTTModel¶
from mptt.models import MPTTModel
class MPTTFood(MPTTModel):
title = models.CharField(max_length=50)
parent = TreeForeignKey("self", blank=True, null=True, related_name="children")
def __unicode__(self):
return self.title
注:理论上,不一定用“parent“去跟字段的名字,MPTT元类中指明即可,如¶
from mptt.models import MPTTModel
class MPTTFood(MPTTModel):
title = models.CharField(max_length=50)
parent_food = TreeForeignKey("self", blank=True, null=True, related_name="children")
class MPTTMeta:
parent_attr = 'parent_food'
def __unicode__(self):
return self.title
但强烈建议,如果能用就用“parent”¶
写admin.py,注册¶
from django.contrib import admin
from models import MPTTFood
class MPTTFoodAdmin(admin.ModelAdmin):
tree_auto_open = 0
list_display = ('title',)
ordering = ('title',)
admin.site.register(MPTTFood,MPTTFoodAdmin)
有关mptt已经结束,关于在前台怎么用数状数据,请看官方文档
4. 安装django-mptt-admin¶
pip install django_mptt_admin
或
下载源码https://github.com/leukeleu/django-mptt-admin
5.配置 django-mptt-admin¶
Add django_mptt_admin to your installed apps in settings.py
6.使用 django-mptt-admin¶
只要在admin.py里继承DjangoMpttAdmin即可
from django.contrib import admin
from models import MPTTFood
from django_mptt_admin.admin import DjangoMpttAdmin
class MPTTFoodAdmin(DjangoMpttAdmin):
tree_auto_open = 0
list_display = ('title',)
ordering = ('title',)
admin.site.register(MPTTFood,MPTTFoodAdmin)
That's All