django后台admin下拉框进⾏过滤
使⽤django admin ⾃带后台
admin后台下拉显⽰的时候需要添加过滤条件,
因为表是⾃⼰关联⾃⼰,同时还需要过滤掉⾃⼰,需要获取当前对象的id,需要获取obj_id
ib 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):
django admin 自定义页面if db_field.name == 'parent_comment':
try:
obj_id = solver_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)
ister(Comment, CommentAdmin)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。