How do you filter autocomplete search results on an admin site based on one (or more) features entered on the current admin object?
In my case, I am designing a database of literary Works
featuring their Authors
and describing their excerpts (e.g., “Chapter 1” from Moby-Dick).
I want to filter the options for the Parent
field of the Work
model to only show works that share one (or more) authors with the Author
already named on the admin page.
I can’t figure out why my current code (below) can’t retrieve the current author_id
and filter works accordingly:
Relevant admin.py
:
class WorkAdmin(admin.ModelAdmin):
autocomplete_fields = [
"author",
"parent",
"form",
"genre",
]
search_fields = [
"title",
"parent__title",
"author__name",
]
list_display = [
"title",
"author",
"parent",
]
list_filter = [
"workinanthology__reviewed",
"anthologies__series",
"anthologies",
"form",
]
inlines = [
WorkInAnthologyInline,
]
def get_search_results(self, request, queryset, search_term):
queryset, may_have_duplicates = super().get_search_results(
request,
queryset,
search_term,
)
author_id = request.GET.get("author_id")
if author_id:
queryset = queryset.filter(author=author_id)
return queryset, False
Relevant models.py
:
class Work(models.Model):
title = models.CharField(
max_length=200,
)
author = models.ForeignKey(
"Author",
on_delete=models.SET_NULL,
null=True,
)
parent = models.ForeignKey(
"Work",
null=True,
on_delete=models.SET_NULL,
blank=True,
verbose_name="Parent work",
)
form = models.ManyToManyField(
"Form",
blank=True,
)
genre = models.ManyToManyField(
"Genre",
blank=True,
)
anthologies = models.ManyToManyField(
"Anthology",
through="WorkInAnthology",
)
is_editor_title = models.BooleanField(
default=False,
verbose_name="Was this work's title imposed by an editor?",
)
class Meta:
unique_together = ("title", "author", "parent")
ordering = ["-id"]
def __str__(self):
return self.title