My Django Foo
model has the following GenericForeignKey
:
content_type = models.ForeignKey(ContentType, blank=True, null=True, on_delete=models.SET_NULL)
object_id = models.PositiveIntegerField(blank=True, null=True)
my_object = GenericForeignKey('content_type', 'object_id')
my_objects
can be instances of Baz
and (rarely) Qux
models. The Qux
model has a foreign key to Baz
. I want to have a searchfield in my Foo admin page that would search by baz_id and yield either instances of Foo that have the Baz
of the given ID in my_object
field or instances of Foo that have Qux
related to the Baz
of the given ID.
Here's what I'm trying to do:
class FooAdmin(...):
# some custom classes and mixins here, neither of which overrides get_search_results()
query_fields_placeholders = {'object_id': 'Baz ID'}
...
...
search_fields = ('object_id',)
def get_search_results(self, request, queryset, search_term):
queryset, use_distinct = super().get_search_results(request, queryset, search_term)
if search_term:
baz_content_type = ContentType.objects.get_for_model(Baz)
qux_content_type = ContentType.objects.get_for_model(Qux)
baz_queryset = queryset.filter(
content_type=baz_content_type, object_id=search_term
)
related_qux_ids = Subscription.objects.filter(baz_id=search_term).values_list(
'id', flat=True
)
qux_queryset = queryset.filter(
content_type=qux_content_type, object_id__in=related_qux_ids
)
queryset = baz_queryset | qux_queryset
return queryset, use_distinct
However, what happens is that only Foo instances that have Baz instances as my_objects are returned by the search and those that have Qux instances in my_object fields seem completely ignored (as if the qux_queryset
part didn't exist at all). Everything looks fine if I just run all these queries in a Django shell or check the underlying SQL, but Django Admin itself seems to somehow interfere with my search.
Any suggestions?