Search code examples
djangosearchbar

Can I use a single search bar for searching different things?


I'm trying to use a single search bar for searching different models. Is it possible to handle it with one view?

my views.py file:

class SearchResultsView(ListView):
    model = Food
    template_name = 'restaurant/food_search_results.html'
    context_object_name = 'data'

    def get_queryset(self):
        query = self.request.GET.get('search')
        if query is not None:
            return Food.objects.filter(name__icontains=query)
        else:
            return Food.objects.none()

my models.py file:

class Food(models.Model):

    name = models.CharField(max_length=100)
    image = models.ImageField(upload_to=upload_path)
    description = models.TextField(max_length=500)
    created = models.DateTimeField(auto_now_add=True)

    meal_category = models.ManyToManyField(MealCategory, related_name="meal")
    food_restaurant_category = models.ManyToManyField(FoodRestaurantCategory, related_name="food_cat")

class Restaurant(models.Model):
    name = models.CharField(max_length=100)

Solution

  • You can use the context to pass the second model filtered list:

    class SearchResultsView(ListView):
        model = Food
        template_name = 'restaurant/food_search_results.html'
        context_object_name = 'data'
    
        def get_queryset(self):
            query = self.request.GET.get('search')
            if query is not None:
                return Food.objects.filter(name__icontains=query)
            else:
                return Food.objects.none()
            
        def get_context_data(self, **kwargs):
            query = self.request.GET.get('search')
            context = super(SearchResultsView, self).get_context_data(**kwargs)
            if query is not None:
                filtered_restaurants= Restaurant.objects.filter(name__icontains=query)
            else:
                filtered_restaurants= Restaurant.objects.none()
    
            context.update({
                'restaurants_list': filtered_restaurants
            })
            return context