对django后台admin下拉框进行过滤的实例

yipeiwu_com6年前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)

以上这篇对django后台admin下拉框进行过滤的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现将Excel转换成为image的方法

我的主要思路是: Excel -> Html -> Image 代码如下: # -*- coding:utf-8 -*- __author__ = 'YangXin' i...

Python 实现异步调用函数的示例讲解

async_call.py #coding:utf-8 from threading import Thread def async_call(fn): def wrapper...

在Python中操作时间之strptime()方法的使用

 strptime()方法分析表示根据格式的时间字符串。返回值是一个struct_time所返回gmtime()或localtime()。 格式参数使用相同的指令使用strft...

简单学习Python time模块

本文针对Python time模块进行分类学习,希望对大家的学习有所帮助。 一.壁挂钟时间 1.time() time模块的核心函数time(),它返回纪元开始的秒数,返回值为浮点数,具...

Python3.4学习笔记之列表、数组操作示例

本文实例讲述了Python3.4列表、数组操作。分享给大家供大家参考,具体如下: python列表,数组类型要相同,python不需要指定数据类型,可以把各种类型打包进去 python列...