[SOLVED] How do I search 2 tables in – Stack Overflow


This Content is from Stack Overflow. Question asked by tinnies

I am continuing to learn Django as a newbie…..I would like some direction in relation to 1 search query against two tables that hold the same headers such as customer names.
So table 1 is customer names from 2022 and table 2 is customer names from 2021.

I can create the models / admin and URL and set the project up.

How do I create a query to search both tables at the same time and display the result?

    def index(request,):

    q = request.GET.get('q')

    if q:
        #this is what is searched against.....ie the columns in our model.py
        vector = SearchVector('name')
        #This is the value the user is searching for:
        query = SearchQuery (q)
        # customers = customer.objects.filter(name__search=q)
        # customers = customer.objects.annotate(search=vector).filter(search=query)
        customers = customer1.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.001).order_by('-rank')
        customers = None
    context = {'customers': customers}
    return render(request, 'index.html', context)

<!doctype html>
<html lang="en">

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">


  {% include 'navbar.html' %}

  <div class="container">

    {% block content %}

      <div class="mb-3">
        <label for="Search Query" class="form-label ">
          <h3>db Search Query</h3>
        <input type="text" class="form-control" aria-describedby="#" name="q">
        <button type="submit" class="btn btn-primary ">Submit</button>
        <button type="submit" class="btn btn-danger">Reset</button>

    {% if customers %}

    <h3><mark>Results:</mark> {{ customer | length }}</h3>

    {% for customer in customers %}

    <table class="table table-striped">
          <th scope="col">Search Result</th>
          <th scope="col">name</th>                  

            <th scope="row">1</th>
            <td>{{ customer.name }}</td>            

      Rank: {{ customer.rank }}

          {% endfor %}

      {% endif %}
  {% endblock %}


  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js"


Django-filter can do it easily!

This Question was asked in StackOverflow by tinnies and Answered by SS_SS It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?