2011-03-15 96 views
2

我正在使用django-mptt創建一個Categories模型,然後將它用作Documents模型的外鍵。類別管理工作正常,類別按預期按樹形順序顯示。不過,在管理中訂購Document模型時遇到兩個問題。在管理中訂購django-mptt外鍵不起作用

管理列表中的文檔正在以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') 

UPDATE FIXED:

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',) 

回答

2

OK - 發現了一些持久性的答案:

爲什麼不正確排序顯示列表?因爲它僅使用第一個字段:

ModelAdmin.ordering集順序來 指定如何對象的名單應在Django管理視圖中 訂購。 這應該是 與模型訂購 參數相同格式的列表或元組。

如果未提供,則Django 管理員將使用該模型的默認 排序。

注意Django只會兌現列表/元組中的第一個 元素;任何其他 將被忽略。

爲什麼選擇下拉菜單的順序不正確?因爲我必須在子類中有一個順序,而不僅僅是抽象模型。

+1

還沒有嘗試過,只需在文檔中閱讀: '在Django 1.4中更改:Django管理員尊重列表/元組中的所有元素;在1.4之前,只有第一個受到尊重 – balazs 2012-05-22 12:21:43