formfield_for_foreignkey似乎无能为力

时间:2018-08-24 17:13:49

标签: django django-admin

我正在此处和其他各个地方使用所示的方案:https://books.agiliq.com/projects/django-admin-cookbook/en/latest/filter_fk_dropdown.html

我的代码如下:

class StudentAdmin(admin.ModelAdmin):

    #...

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        groups = [group.name for group in request.user.groups.all()]
        if 'principal' in groups:
            school = request.user.principal.school
            if db_field == "room":
                kwargs['queryset'] = Room.objects.filter(school=school)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

    list_display = ('surname','givennames', 'room')
    list_filter = ('room',)

我已经验证了代码已被调用并且 school 设置正确,但是没有对选择器进行过滤。也就是说,我可以看到所有 room 实例,无论它们对 school 的价值如何。

一旦部署在现实世界中,该列表将显示太多项目,其中大部分是用户不希望看到的,也不应该看到。但是过滤没有发生。有什么想法我错过了吗?

学校本身是房间的外键是否有意义?在其他过滤器中效果很好

我也希望对选择视图的list_filter进行类似的过滤,但是这里甚至没有调用此代码。建议非常感谢。

2 个答案:

答案 0 :(得分:1)

将db_field检查更改为此:

 if db_field.name == "room":

答案 1 :(得分:0)

遵循此处和其他地方所示的方案:https://books.agiliq.com/projects/django-admin-cookbook/en/latest/filter_fk_dropdown.html

我修复的代码如下:

class StudentAdmin(admin.ModelAdmin):

#...

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    groups = [group.name for group in request.user.groups.all()]
    if 'principal' in groups:
        school = request.user.principal.school
        if db_field.name == "room": # This was the error; 
                                    # nothing wrong with the example; 
                                    # I just bobbled the retranscription
            kwargs['queryset'] = Room.objects.filter(school=school)
    return super().formfield_for_foreignkey(db_field, request, **kwargs)

list_display = ('surname','givennames', 'room')
list_filter = ('room',)