问题类似于Django "list_filter" based on the admin queryset。我需要根据当前用户使用list_filter。但是在我的情况下,字段跨度关系使用__查找。在RelatedFieldListFilter上没有有用的“查找”方法。我的方法产生了下一个代码:
def custom_titled_filter(title):
class Wrapper(admin.FieldListFilter):
def __new__(cls, field, request, *args, **kwargs):
instance = admin.FieldListFilter.create(field, request, *args, **kwargs)
instance.title = title
rel_model = field.remote_field.model
qs = rel_model._default_manager.all()
if not request.user.is_superuser:
qs = qs.filter(user=request.user)
choice_func = operator.attrgetter(
field.remote_field.get_related_field().attname
if hasattr(field.remote_field, 'get_related_field')
else 'pk'
)
instance.lookup_choices = [
(choice_func(x), str(x)) for x in qs
]
return instance
return Wrapper
当前版本的Django是否有更好的方法?