限制 ModelAdmin 中外键的选项 returns "Select a valid choice"

Limiting the options of foreign key in ModelAdmin returns "Select a valid choice"

我正试图将选项限制为特定用户的管理应用程序中的外键(我试图限制的字段称为学校)。这就是我的代码的样子 - 不幸的是,当我尝试编辑学生(通过单击他们的名字)时有两个问题(如下所述)。

1.The 学校的默认值为 --

2.When 我 select 从下拉列表中选择正确的学校并尝试保存 我在学校字段中收到错误消息

Select a valid choice. That choice is not one of the available choices.

这是它的样子

class modelStudentAdmin(admin.ModelAdmin):   

     def get_queryset(self, request):
        qs = super(modelStudentAdmin, self).get_queryset(request)

        if request.user.is_superuser:
            return qs
        else:
            schoolInstance = modelSchool.objects.get(user=request.user)
            qs = modelStudent.objects.filter(school=schoolInstance)
            return qs

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if request.user.is_superuser:
            return super(modelStudentAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

        #Not superuser only staff
        if db_field.name == 'school':
            t = modelSchool.objects.filter(user=request.user).values_list("school_name",flat=True)
            kwargs['queryset'] = t

        return super(modelStudentAdmin,self).formfield_for_foreignkey(db_field, request, **kwargs)

现在如果我删除方法

def formfield_for_foreignkey(self, db_field, request, **kwargs):

一切正常,但我无法限制外键。关于我可能做错了什么的任何建议?

尝试替换

 t = modelSchool.objects.filter(user=request.user).values_list("school_name",flat=True)

有了这个

modelSchool.objects.filter(user=request.user)

您不需要 value_list 您的查询集。