Django查询数据库

时间:2017-02-22 10:13:31

标签: python django

我正在尝试在django中实现搜索。

我的观点如下:

    search_term = request.GET['search_term']

    customers = Customer.objects.filter(
        Q(chassis__icontains=search_term) | Q(registration__icontains=search_term) |
        Q(email__icontains=search_term) | Q(firstname__icontains=search_term) |
        Q(lastname__icontains=search_term))
    calculations_data = []
    if customers:
        for customer in customers:

            try:
                calculation = Calculations.objects.get(customer=customer, user=request.user)
                calculations_data.append({
                    'calculation': calculation,
                    'price': price_incl_vat(calculation.purchase_price),
                    'customer_fullname': '{} {} '.format(customer.firstname, customer.lastname),
                    'car_chassis': customer.chassis,
                    'car_registration': customer.registration,

                })
            except Calculations.DoesNotExist:
                pass

    context = {'search_term': search_term, 'total_result': len(calculations_data), 'calculation_data': calculations_data}
    return render(request, 'master/search.html', context)

我有两个模型,calculationscustomer。在内部计算我有客户作为ForeignKey,但它可以是空的。因此,每次计算都不需要有客户。

在我的例子中,如果我有search term结果是好的,但如果没有搜索词,那么我只得到有客户的计算。

但我需要的是,如果没有search_term,我想得到所有的计算。

是否有更好的方法来编写查询?

感谢。

2 个答案:

答案 0 :(得分:1)

由于结果取决于search_term的可用性,为什么不在if-else上使用search_term

search_term = request.GET.get('search_term', None)
if search_term:
    # when search term is not None
    # get relevant calculations
else:
    calculations = Calculations.objects.all()
    # rest of code

通过将search_term对象直接放在None本身(而不是获取相关客户,然后找到),您可以在Q不是Calculations.objects.filter()时进一步简化代码相关计算)。在Django中,您可以查询Q个对象中外键的属性。您首先获取客户,然后使用这些结果查找计算。这将增加对数据库的查询次数。

您可以执行以下操作:

calculations = Calculations.objects.filter(
                   Q(customer__email__icontains=search_term) | 
                   Q(customer__chassis_icontains=search_term)| 
                   Q(....)).select_related('customer')

相关链接:
1. Lookups that span relationships
2. select_related

答案 1 :(得分:0)

试试这个:

if customers:
        try:
            calculations = Calculations.objects.filter(user=request.user)
            if customers:
                calculations=calculations.filter(customer__in=customers)

            for calculation in calculations:
                 calculations_data.append({
                    'calculation': calculation,
                    'price': price_incl_vat(calculation.purchase_price),
                    'customer_fullname': '{} {} '.format(customer.firstname, customer.lastname),
                    'car_chassis': customer.chassis,
                    'car_registration': customer.registration,
                 })
        except Calculations.DoesNotExist:
            pass