If i see those questions, i understand, how many people works with django and completely don't understand it.
First.
In the Django admin, I have an Inline
,
and I would like to filter the list of rows by the parent object.
You don't need to do it in Inline
object. Inline
is only the helper, who organize creation of InlineFormSet
.
And on the first lines of __init__
of your InlineFormSet
- it get parent_object
and made "filter the list of rows by the parent object" for inline.queryset. (django.forms.models.py, row 904 in Django 4.07)
It means, if you want to filter inline.queryset
by parent_id
before, it has not any reason to do it twice.
Second.
Please avoid loops. for example - get_inline_instances is good to set parent_object. But not in form of @pakawinz answer. You can do it better:
def get_inline_instances(self, request, obj=None):
return ((instance, setattr(instance, 'parent_object', obj))[0] for instance in super().get_inline_instances(request, obj))
And you can do it much better:
def get_inlines(self, request, obj):
"""Hook for specifying custom inlines."""
return (type(inline.__name__, (inline,) {'parent_object': obj}) for inline in super().get_inlines(request, obj))
Second example add parent_object
like an attribute to inline_class
. it give you possibility to get parent_object
in classmethods
too.
Third
Your question already has the best possibility to give an inline a parent_object to use it in queryset
def get_formset_kwargs(self, request, obj, inline, prefix):
inline.parent_obj = obj
return super().get_formset_kwargs(request, obj, inline, prefix)
Four
@NackiE23 tells you a better way to get parent_object
.
Please don't use path.split()
, this is not works for add_view
in ModelAdmin
. in your case:
def get_queryset(self, request):
... # your staff
resolved = resolve(request.path_info) # this is a better way to get it.
if resolved.kwargs.get('object_id'):
event = resolved.func.__self__.get_object(request, resolved.kwargs.get('object_id'), to_field=None) # please check if you don't need to_field
else:
event = resolved.func.__self__.model()
Please check, how work your solution not only for change_view, also for add_view too.
Last
I work only with django.admin.contrib
more than 7 years. You can find my Talks about django.admin.contrib on PyCon RU 2021, PyCon DE 2022, DjangoCon EU 2022 and, later, on DjangoCon US 2022.
With my experience I think, probably, you do something unnecessary in your code. But i am not sure, therefore i write you some solutions above.