我正在使用 django-mptt 创建一个 Categories 模型,然后将其用作 Documents 模型的外键。类别管理员工作正常,类别按预期以树状顺序显示。但是,我在管理员中订购 Document 模型时遇到了两个问题。
管理列表中的文档以 ID 顺序而不是类别顺序列出编辑屏幕中类别的下拉列表以类别 ID 顺序列出。请注意,出于另一个原因,我将抽象类用于类别。
为什么我在模型中指定的顺序被忽略了?
模型.py
class Category(MPTTModel):
parent = models.ForeignKey('self', related_name="children")
name = models.CharField(max_length=100)
class Meta:
abstract = True
ordering = ('tree_id', 'lft')
class MPTTMeta:
ordering = ('tree_id', 'lft')
order_insertion_by = ['name',]
class CategoryAll(Category):
class Meta:
verbose_name = 'Category for Documents'
verbose_name_plural = 'Categories for Documents'
class Document(models.Model):
title = models.CharField(max_length=200)
file = models.FileField(upload_to='uploads/library/all', blank=True, null=True)
category = models.ForeignKey(CategoryAll)
class Meta:
ordering = ('category__tree_id', 'category__lft', 'title')
管理员.py
class DocAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'category')
list_filter = ('author','category')
ordering = ('category__tree_id', 'category__lft', 'title')
更新修复:
模型.py
class Category(MPTTModel):
parent = models.ForeignKey('self', related_name="children")
name = models.CharField(max_length=100)
class Meta:
abstract = True
class MPTTMeta:
order_insertion_by = ['name',]
class CategoryAll(Category):
class Meta:
verbose_name = 'Category for Documents'
verbose_name_plural = 'Categories for Documents'
ordering = ('lft',)
class Document(models.Model):
title = models.CharField(max_length=200)
file = models.FileField(upload_to='uploads/library/all', blank=True, null=True)
category = models.ForeignKey(CategoryAll)
class Meta:
ordering = ('category__tree_id', 'category__lft', 'title')
管理员.py
class DocAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'category')
list_filter = ('author','category')
ordering = ('category__lft',)