简体   繁体   English

Django在同一数据表中的多个字段内搜索查询

[英]Django Search query within multiple fields in same data table

This is my models.py file. 这是我的models.py文件。

class CustomerInfo(models.Model):
    customer_name=models.CharField('Customer Name', max_length=50)
    customer_mobile_no = models.CharField('Mobile No', null=True, blank=True,max_length=12)
    customer_price=models.IntegerField('Customer Price')
    customer_product_warrenty = models.CharField('Product Warrenty',null=True, blank=True,max_length=10)
    customer_sell_date = models.DateTimeField('date-published', auto_now=True)
    customer_product_id=models.CharField('Product ID',max_length=150,null=True, blank=True)
    customer_product_name=models.CharField('Product Name', max_length=50)
    customer_product_quantity=models.IntegerField('Quantity',default=1)


    def __str__(self):
        return self.customer_name

Now I want to search in muliple fieds like as customer_name, customer_mobile_no,customer_product_id etc. So I created views.py file 现在我想搜索多个fid,如customer_name, customer_mobile_no,customer_product_id等。所以我创建了views.py文件

def customerPage(request):
    customers = CustomerInfo.objects.all()

    if request.method =="GET":
       customerid = request.GET['customer_id']

       try:
           customers = CustomerInfo.objects.get(pk=customerid)
           cus_name = CustomerInfo.objects.filter(customer_name__contains=customerid)
           mobile_number = CustomerInfo.objects.filter(customer_mobile_no__contains=customerid)



           return render(request, 'shop/customer.html', {"cus_name": cus_name,"mobile_number": mobile_number, "customers": 'customers', "site_name": "Moon Telecom"})
       except:
           return render(request, 'shop/customer.html', {"error": "Not found any info"})

    return render(request, 'shop/customer.html', {'customers': customers})

and this is my html file 这是我的html文件

{% extends "shop/base.html" %}

{% block content_area %}

<div class="col-lg-4">
    <div class="customer_search" >
        <form action="{% url "shop:customerPage" %}" method="GET">
            {% csrf_token %}
            <div class="form-group">
                <label for="customer_id">Id:</label>
                <input type="text" class="form-control" id="customer_id" placeholder="Enter customer ID" name="customer_id">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
        </form>
    </div>
</div>

<div class="col-lg-8 customers_info">
    {% if error %}
    <div class="alert alert-danger">
        <strong>{{error}}</strong>
    </div>
    {% endif %}



{% if cus_name %}

    {% for x in cus_name  %}
    <p>{{x.customer_name}}</p>
    {% endfor %}
{% else %}
<p>nothing foung</p>
{% endif %}


{% if customers %}
    <table class="table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Mobile No</th>
                <th>Product Name</th>
                <th>Price</th>
                <th>Date</th>
                <th>Product ID</th>
                <th>Warrenty</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><a href="/shop/{{customers.id}}/customerprofile">{{customers.customer_name}}</a></td>
                <td>{{customers.customer_mobile_no}}</td>
                <td>{{customers.customer_product_name}}</td>
                <td>{{customers.customer_price}} TK</td>
                <td>{{customers.customer_sell_date}}</td>
                <td>{{customers.customer_product_id}}</td>
                <td>{% if customers.customer_product_warrenty == '' %}
                <b>No Warrenty</b>
                {% else %}
                 <b>{{customers.customer_product_warrenty}}</b> Month
                {% endif %}
                </td>

            </tr>
        </tbody>
    </table>
     {% else %}
    <p>nothing found</p>
    {% endif %}


</div>



{% endblock  %}

I got results If I use POST method and customers = CustomerInfo.objects.get(pk=customerid) When I searched one field, I have got my results but When I start multiple search query from the database. 我得到了结果如果我使用POST方法和customers = CustomerInfo.objects.get(pk=customerid)当我搜索一个字段时,我得到了我的结果但是当我从数据库开始多个搜索查询时。 I cant get any info. 我无法得到任何信息。 I want to search multiple fields within CustomerInfo model. 我想在CustomerInfo模型中搜索多个字段。 Also, I was trying others mehtod but not working. 此外,我正在尝试别人mehtod但不工作。

You need to search using multiple fields in one query. 您需要在一个查询中使用多个字段进行搜索。 And looking at your code, i presume that the conditions are joined using OR . 看看你的代码,我假设使用OR连接条件。

This problem can be solved using django ORM's Q object 使用django ORM的Q对象可以解决这个问题

What it allows you do is to chain multiple filtering conditions together and connect them logically. 它允许您做的是将多个过滤条件链接在一起并在逻辑上连接它们。

So, if you have 3 conditions and they are logically connected as : Condition 1 OR Condition 2 AND Condition 3 using Q you can write them as : 因此,如果您有3个条件并且它们在逻辑上连接为: Condition 1 OR Condition 2 AND Condition 3使用Q您可以将它们写为:

Q(Condition1) | Q(Condition1) | Q(Conditon2) & Q(Condition2) . Q(Conditon2) Q(Condition2)

In your case the 3 different searches of filterings can be performed as: 在您的情况下,可以执行3种不同的过滤搜索:

filtered_customers = CustomerInfo.objects.filter( Q(pk = int(customerid)) | Q(customer_name__contains = str(customerid)) | Q(customer_mobile_no__contains = str(customerid)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM