Django Admin設(shè)置應(yīng)用程序及模型順序方法詳解
Django默認(rèn)情況下,按字母順序?qū)δP瓦M(jìn)行排序。因此,Event應(yīng)用模型的順序?yàn)镋pic、EventHero、EventVillain、Event
假設(shè)你希望順序是
EventHero、EventVillain、Epic、Event。
用于呈現(xiàn)后臺(tái)indxe頁面的模板為admin/index.html,對(duì)應(yīng)的視圖函數(shù)為 ModelAdmin.index。
def index(self, request, extra_context=None): ''' Display the main admin index page, which lists all of the installed apps that have been registered in this site. ''' app_list = self.get_app_list(request) context = { **self.each_context(request), ’title’: self.index_title, ’app_list’: app_list, **(extra_context or {}), } request.current_app = self.name return TemplateResponse(request, self.index_template or ’admin/index.html’, context)
默認(rèn)的get_app_list方法用于設(shè)置模型的順序。
def get_app_list(self, request): ''' Return a sorted list of all the installed apps that have been registered in this site. ''' app_dict = self._build_app_dict(request) # Sort the apps alphabetically. app_list = sorted(app_dict.values(), key=lambda x: x[’name’].lower()) # Sort the models alphabetically within each app. for app in app_list: app[’models’].sort(key=lambda x: x[’name’]) return app_list
因此,可以通過覆蓋get_app_list方法來修改顯示順序:
class EventAdminSite(AdminSite): def get_app_list(self, request): ''' Return a sorted list of all the installed apps that have been registered in this site. ''' ordering = { 'Event heros': 1, 'Event villains': 2, 'Epics': 3, 'Events': 4 } app_dict = self._build_app_dict(request) # a.sort(key=lambda x: b.index(x[0])) # Sort the apps alphabetically. app_list = sorted(app_dict.values(), key=lambda x: x[’name’].lower()) # Sort the models alphabetically within each app. for app in app_list: app[’models’].sort(key=lambda x: ordering[x[’name’]]) return app_list
以上代碼app[’models’].sort(key=lambda x: ordering[x[’name’]])用來設(shè)置默認(rèn)順序。修改后效果如下。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ThinkPHP5 通過ajax插入圖片并實(shí)時(shí)顯示(完整代碼)2. ASP.NET MVC通過勾選checkbox更改select的內(nèi)容3. Android實(shí)現(xiàn)圖片自動(dòng)切換功能(實(shí)例代碼詳解)4. jsp+mysql實(shí)現(xiàn)網(wǎng)頁的分頁查詢5. Python使用oslo.vmware管理ESXI虛擬機(jī)的示例參考6. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼7. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁8. 解決Python paramiko 模塊遠(yuǎn)程執(zhí)行ssh 命令 nohup 不生效的問題9. JavaScript Tab菜單實(shí)現(xiàn)過程解析10. 使用AJAX(包含正則表達(dá)式)驗(yàn)證用戶登錄的步驟
