django admin inlines:从 formfield_for_foreignkey 获取对象

2022-01-25 00:00:00 python django django-admin

问题描述

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

I am trying to filter the options shown in a foreignkey field, within a django admin inline. Thus, I want to access the parent object being edited. I have been researching but couldn't find any solution.

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 是空的,所以我无法从那里获取对象.

I have verified that kwargs is empty when editing an object, so I can't get the object from there.

有什么帮助吗?谢谢


解决方案

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

To filter the choices available for a foreign key field in an admin inline, I override the form so that I can update the form field's queryset attribute. That way you have access to self.instance which is the object being edited in the form. So something like this:

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,它应该可以完成您描述的操作.

You don't need to use formfield_for_foreignkey if you do the above and it should accomplish what you described.

相关文章