时间:2020-12-17 02:09:24 | 栏目:Python代码 | 点击:次
使用django admin 自带后台
admin后台下拉显示的时候需要添加过滤条件,
因为表是自己关联自己,同时还需要过滤掉自己, 需要获取当前对象的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)