2

我正在使用 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',)
4

1 回答 1

2

好的 - 找到了一些持久性的答案:

为什么显示列表排序不正确?因为它只使用第一个字段:

ModelAdmin.ordering 设置排序以指定对象列表在 Django 管理视图中的排序方式。这应该是与模型的排序参数格式相同的列表或元组。

如果没有提供,Django 管理员将使用模型的默认排序。

注意 Django 只会尊重列表/元组中的第一个元素;任何其他人都将被忽略。

为什么选择下拉菜单没有正确排序?因为我必须在子类中有一个顺序,而不仅仅是抽象模型。

于 2011-03-15T16:46:03.347 回答