我希望有一棵树可以模仿带有文件夹和文件的文件系统。文件夹和文件将由具有不同字段属性的不同模型定义。
模型:
from mptt.models import MPTTModel, TreeForeignKey
class Folder(MPTTModel):
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
name = models.CharField(max_length=50)
type = models.CharField(max_length=50)
class File(MPTTModel):
parent= TreeForeignKey(Document)
filename = models.CharField(max_length=255)
encoding = models.CharField(max_length=20)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
创建一些文件夹和文件:
from shapefile.models import Folder, File
root = Folder.objects.create(name="Root")
download = Folder.objects.create(name="Download", parent=root)
upload = Folder.objects.create(name="Upload", parent=root)
File.objects.create(filename="Test", encoding="UTF-8", parent=download)
Shoul有:
> Root
> --Download
> ----Test
> --Upload
如何在视图和模板中检索此树?
修改
文件未作为文件夹的节点插入:
file = File.objects.get(filename="Test")
file.get_ancestors()
>>> []
答案 0 :(得分:5)
您可以将MPTTModel与generic relation结合使用 来自 contenttypes框架。 您可以通过将“django.contrib.contenttypes”添加到INSTALLED_APPS设置来启用它。
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
class TreeItem(MPTTModel):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
class Folder(models.Model):
name = models.CharField(max_length=50)
type = models.CharField(max_length=50)
class File(models.Model):
filename = models.CharField(max_length=255)
encoding = models.CharField(max_length=20)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
mptt documentacion说明了如何访问模板中的树。