django admin inlines: get object from formfield_for_foreignkey
Another way, that, IMHO, feels cleaner than, but is similar to @erichonkanen's answer is something like this:
class ProjectGroupMembershipInline(admin.StackedInline):
# irrelevant bits....
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "group":
try:
parent_id = request.resolver_match.args[0]
kwargs["queryset"] = Group.objects.filter(some_column=parent_id)
except IndexError:
pass
return super().formfield_for_foreignkey(db_field, request, **kwargs)
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)
You don't need to use formfield_for_foreignkey
if you do the above and it should accomplish what you described.