2019-07-26 13:42:47 3490瀏覽
今天千鋒扣丁學堂Python培訓老師給大家分享一篇關(guān)于django后臺admin下拉框進行過濾的實例詳解,首先使用djangoadmin自帶后臺,admin后臺下拉顯示的時候需要添加過濾條件,因為表是自己關(guān)聯(lián)自己,同時還需要過濾掉自己,需要獲取當前對象的id,需要獲取obj_id。
from django.contrib import admin from .models import Comment # actions添加模型動作 def disable_commentstatus(modeladmin, request, queryset): queryset.update(is_enable=False) def enable_commentstatus(modeladmin, request, queryset): queryset.update(is_enable=True) disable_commentstatus.short_description = '隱藏評論' enable_commentstatus.short_description = '顯示評論' class CommentAdmin(admin.ModelAdmin): list_display = ('id', 'commentator', 'article', 'parent_comment', 'is_enable', 'created_time') list_display_links = ('id', 'commentator') list_filter = ('commentator', 'article', 'is_enable') actions = [disable_commentstatus, enable_commentstatus] def formfield_for_foreignkey(self, db_field, request, *args, **kwargs): if db_field.name == 'parent_comment': try: obj_id = request.resolver_match.args[0] #這里獲取當前對象id,非常重要 kwargs['queryset'] = Comment.objects.filter(parent_comment=None).exclude(id=int(obj_id)) # 添加過濾條件 except: kwargs['queryset'] = Comment.objects.filter(parent_comment=None) return super(CommentAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Comment, CommentAdmin)
【關(guān)注微信公眾號獲取更多學習資料】 【掃碼進入Python全棧開發(fā)免費公開課】
查看更多關(guān)于"Python開發(fā)資訊"的相關(guān)文章>