0

Help to unite search in several models. I have two models Apartment and Houses. These models have the same strings State. According to them, I customize the search in views.py. It looks like this:

views.py

def search(request):
    queryset_list = Houses.objects.order_by('-list_date')

     if 'state' in request.GET:
        state = request.GET['state']
        if state:
            queryset_list = queryset_list.filter(state__iexact=state)

context = {
        'queryset_list': queryset_list,
    }

    return render(request, '/search-templates/search.html', context)

As a result, I see Houses from the selected region. I understand that the search is conducted in the model Houses. It works great!

queryset_list = Houses.objects.order_by('-list_date')

Question: How to combine search? Show objects from two models Apartment and Houses.

Thank you in advance!

I.Z.
  • 177
  • 1
  • 1
  • 13

1 Answers1

1

You should write two query:

houses_list = Houses.objects.order_by('-list_date')
apartment_list = Apartment..objects.order_by('-list_date')

if state:
            houses_list = houses_list.filter(state__iexact=state)
            apartment_list = apartment_list.filter(state__iexact=state)

And then combine your query_sets like this https://stackoverflow.com/a/434755/6265279

from itertools import chain
queryset_list = list(chain(houses_list, apartment_list))

Saeed Alijani
  • 313
  • 2
  • 13
  • **Saeed Alijani**, this is exactly what I need. Everything works, thank you so much for the answer. – I.Z. Jul 30 '19 at 21:51