在管理员工作中订购django-mptt外键

时间:2011-03-15 11:52:26

标签: django django-mptt

使用django-mptt创建一个Categories模型,然后将其用作Documents模型的外键。 Categories管理工作正常,类别按树的顺序显示。但是,我在admin中订购Document模型时遇到两个问题。

管理员列表中的文档列在id顺序而非类别顺序中 编辑屏幕中“类别”的下拉列表列在类别ID顺序中。请注意,我出于另一个原因使用抽象类作为类别。

为什么我在模型中指定的顺序被忽略?

Models.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')

Admin.py

class DocAdmin(admin.ModelAdmin):

  list_display = ('title', 'author', 'category')
  list_filter = ('author','category')
  ordering = ('category__tree_id', 'category__lft', 'title')

更新已修复:

Models.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')

Admin.py

class DocAdmin(admin.ModelAdmin):

  list_display = ('title', 'author', 'category')
  list_filter = ('author','category')
  ordering = ('category__lft',)

1 个答案:

答案 0 :(得分:2)

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

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

  

ModelAdmin.ordering将排序设置为   指定对象列表应该如何   在Django管理员视图中排序。   这应该是一个列表或元组   与模型的订购格式相同   参数。

     

如果未提供,则为Django   admin将使用该模型的默认值   排序

     

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

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

相关问题