我正在尝试过滤django admin内联中的Foreignkey字段中显示的选项。因此,我想访问正在编辑的父对象。我一直在研究,但找不到任何解决方案。

class ProjectGroupMembershipInline(admin.StackedInline):
    model = ProjectGroupMembership
    extra = 1
    formset = ProjectGroupMembershipInlineFormSet
    form = ProjectGroupMembershipInlineForm

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        if db_field.name == 'group':
            kwargs['queryset'] = Group.objects.filter(some_filtering_here=object_being_edited)
        return super(ProjectGroupMembershipInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

我已验证在编辑对象时kwargs为空,因此无法从那里获取对象。

有什么帮助吗?谢谢

最佳答案

为了过滤admin内联中可用于外键字段的选项,我覆盖了表单,以便可以更新表单字段的queryset属性。这样,您就可以访问self.instance,它是表单中正在编辑的对象。所以像这样:

class ProjectGroupMembershipInlineForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ProjectGroupMembershipInlineForm, self).__init__(*args, **kwargs)
        self.fields['group'].queryset = Group.objects.filter(some_filtering_here=self.instance)

如果执行上述操作,则无需使用formfield_for_foreignkey,它就可以完成您所描述的内容。

关于python - django admin内联: get object from formfield_for_foreignkey,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21337142/

10-11 11:35