Django Admin設(shè)置應(yīng)用程序及模型順序方法詳解
Django默認(rèn)情況下,按字母順序?qū)δP瓦M(jìn)行排序。因此,Event應(yīng)用模型的順序為Epic、EventHero、EventVillain、Event
假設(shè)你希望順序是
EventHero、EventVillain、Epic、Event。
用于呈現(xiàn)后臺indxe頁面的模板為admin/index.html,對應(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)順序。修改后效果如下。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 如何通過vscode運行調(diào)試javascript代碼2. JavaScript設(shè)計模式之策略模式實現(xiàn)原理詳解3. idea向System.getenv()添加系統(tǒng)環(huán)境變量的操作4. Java操作Redis2種方法代碼詳解5. python GUI庫圖形界面開發(fā)之PyQt5信號與槽基礎(chǔ)使用方法與實例6. python如何寫個俄羅斯方塊7. python b站視頻下載的五種版本8. JAVA抽象類及接口使用方法解析9. 《CSS3實戰(zhàn)》筆記--漸變設(shè)計(一)10. python GUI庫圖形界面開發(fā)之PyQt5信號與槽的高級使用技巧裝飾器信號與槽詳細(xì)使用方法與實例
