Nikhar Bajaj
Nikhar Bajaj

Reputation: 11

How to Filter table by column in django

I was trying to filter my columns in my django project template Currently I am able to search in the table and display the rows that have that that value But I would like to add a dropdown menu that would ask for a particular column value and then filter based on that value

currently my code is

views.py

def user_profile(request):
    q = request.GET.get('q','')
    custom = Customer.objects.all()
    if q: 
        custom1=custom.filter(name__contains=q)
        custom2=custom.filter(Product__contains=q)
        custom3=custom.filter(L3__contains=q)
        custom4=custom.filter(Server_Type__contains=q)
        custom5=custom.filter(Version__contains=q)
        custom6=custom.filter(Status__contains=q)
        custom7=custom.filter(PM__contains=q)
        custom8=custom.filter(CDM__contains=q)
        custom = custom1 | custom2 | custom3 | custom4 | custom5 | custom6 | 
                 custom7 | custom8

here name product l3 are my fields from my model that I would like to filter from

in my home.html

 <input type="text" class="text_field" id="search" placeholder="Search for..." required>
<input type="button" class="button" onclick="go()" value="go" id="submit">

my js.js

function go(){
    // alert("hellonikhar");
    var q = document.getElementById("search").value;

    window.open("/?q="+q,"_self");
}

I am storing the value entered in the textbox in var q and displaying the data but i would like to add a dropdown first which would choose the field and then q should filter based on only that column

Upvotes: 0

Views: 2936

Answers (3)

Ankit Kumar Rathod
Ankit Kumar Rathod

Reputation: 533

Could you please try below query

Customer.objects.filter(Q(name__icontains=q)
                   |Q(Product__icontains=q)
                   |Q(L3__icontains=q)
                   |Q(Server_Type__icontains=q)
                   |Q(Version__icontains=q)
                   |Q(Status__icontains=q)
                   |Q(PM__icontains=q)
                   |Q(CDM__icontains=q)
                   )

Upvotes: 0

TARUN KUMAR
TARUN KUMAR

Reputation: 141

For adding a dynamic dropdown send column names from the backend.

<select name="columns">
    {% for column in columns %}
            <option value="{{column.name}}">Column {{column.id}}: {{column.name}}</option>
    {% endfor %}
</select>

Upvotes: 1

TARUN KUMAR
TARUN KUMAR

Reputation: 141

Add a dropdown with id as the column name and filter the objects by using that column value.

Customer.objects.filter(**{columnName:columnValue})

Upvotes: 0

Related Questions