Django filter_horizo​​ntal过滤

时间:2016-10-03 14:55:46

标签: django django-admin

我有2个与M2M关系相关的模型。我在管理员中使用filter_horizontal来编辑我的实体。

但是,我想控制filter_horizontal窗口小部件左侧显示的内容。例如,我想过滤并仅显示符合某些标准的实体。

2 个答案:

答案 0 :(得分:6)

我想我找到了它!

class MyModelAdmin(admin.ModelAdmin):
def formfield_for_manytomany(self, db_field, request, **kwargs):
    if db_field.name == "cars":
        kwargs["queryset"] = Car.objects.filter(owner=request.user)
    return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

ModelAdmin.formfield_for_manytomany(db_field, request, **kwargs)

答案 1 :(得分:0)

这个主题在Django管理员中总是很棘手。我想在内联防御中你可以做这样的事情:

班级BAdmin(admin.TabularInline):     ...

def get_queryset(self, request):
    qs = super(BAdmin, self).get_queryset(request)
    return qs.filter(user=request.user)

https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset