python 用于GenericForeignKey字段的django管理过滤器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 用于GenericForeignKey字段的django管理过滤器相关的知识,希望对你有一定的参考价值。
# Found here: https://djangosnippets.org/snippets/10564/ and modified
# How use:
#
# #models.py
# class ObjectWithGenericForeignKey(model.Model):
# content_type = models.ForeignKey(ContentType)
# object_id = models.PositiveIntegerField()
# content_object= GenericForeignKey('content_type', 'object_id', for_concrete_model=False)
#
# #admin.py
# class CommentAdmin(admin.ModelAdmin):
# list_filter = (get_generic_foreign_key_filter(u'Filter title'),)
def get_generic_foreign_key_filter(title, parameter_name=u'', separator='-', content_type_id_field='content_type_id', object_id_field='object_id') :
class GenericForeignKeyFilter(SimpleListFilter):
def __init__(self, request, params, model, model_admin):
self.separator = separator
self.title = title
self.parameter_name = u'generic_foreign_key_' + parameter_name
super(GenericForeignKeyFilter, self).__init__(request, params, model, model_admin)
def lookups(self, request, model_admin):
filter = object_id_field + '__isnull' # for fields with null=True
qs = model_admin.model.objects.exclude(**{ filter: True })\
.order_by(content_type_id_field, object_id_field)\
.distinct(content_type_id_field, object_id_field)\
.values_list(content_type_id_field, object_id_field)
return [
(
'{1}{0.separator}{2}'.format(self, *content_type_and_obj_id_pair),
ContentType.objects
.get(id=content_type_and_obj_id_pair[0])
.model_class()
.objects.get(pk=content_type_and_obj_id_pair[1])
.__str__()
)
for content_type_and_obj_id_pair
in qs
]
def queryset(self, request, queryset):
try :
content_type_id, object_id = self.value().split(self.separator)
return queryset.filter(**({
content_type_id_field:content_type_id,
object_id_field:object_id
}))
except:
return queryset
return GenericForeignKeyFilter
以上是关于python 用于GenericForeignKey字段的django管理过滤器的主要内容,如果未能解决你的问题,请参考以下文章
python用于啥方向
用于 Maya 的 Python 命令:attributeQuery 不适用于 imagePlane 属性“colorSpace”
从 boost::python::object 列表中获取单个元素,用于 python 例程
python 用于解析Arguemtns的Python脚本
python 用于python的C风格结构
python 用于列表的python习语[dict]