2👍
By override the default get_search_results
method, the following code Generally works, but still got a little problem.
def get_search_results(self, request, queryset, search_term):
"""Override to Include searching `product__name` which is a
GenericForeignKey Field of all product types.
Returns a tuple containing a queryset to implement the search,
and a boolean indicating if the results may contain duplicates.
"""
products = [v for k, v in pro_models.PRODUCT_DICT.iteritems()]
generic_queryset = queryset
product_list = list()
for bit in search_term.split():
for product in products:
product_queryset = product.objects.filter(
Q(name__icontains=bit))
product_list += list(product_queryset)
generic_query = [Q(**{
'content_type': ContentType.objects.get_for_model(product),
'object_id': product.id
}) for product in product_list]
if generic_query:
generic_queryset = generic_queryset.filter(
reduce(operator.or_, generic_query))
else:
generic_queryset = generic_queryset.none()
default_queryset, use_distinct = \
super(OrderAdmin, self).get_search_results(
request,
queryset,
search_term
)
return default_queryset | generic_queryset, use_distinct
👤Eric
Source:stackexchange.com