如何获得多个字段与django过滤器图标 [英] How to get more than one field with django filter icontains

查看:135
本文介绍了如何获得多个字段与django过滤器图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的查询搜索与我所有的模型字段进行比较,但是我无法确定如何在多个字段中执行此操作。



我的代码。

 费用= Expense.objects.filter(user = request.user.id).order_by('date') 

q = request.GET ['q']
result = expense.filter(name__icontains = q)

我想检入:名称金额类别



提前感谢

解决方案

从Django文档:



关键字参数查询 - 在filter()等)中一起使用AND,如果需要执行更复杂的查询(例如,使用OR语句的查询),可以使用Q对象。

 从django.db.models导入Q 
expenses.objects.filter(
Q(name__icontains = q)| Q(amount__icontains = q)| Q(category__icontains = q)

/ pre>

我是不确定您的模型中的金额和类别的类型,所以图标可能无法在其上工作。



请参阅此链接


I am trying to compare my query search to all my model fields, but I can't figure how to do it in more than one field.

this is my code.

expense = Expense.objects.filter(user=request.user.id).order_by('date')

q = request.GET['q']
result = expense.filter(name__icontains=q)

I want to check in: name, amount, category

Thanks in advance

解决方案

From Django documentation:

"Keyword argument queries – in filter(), etc. – are "AND"ed together. If you need to execute more complex queries (for example, queries with OR statements), you can use Q objects."

from django.db.models import Q
expense.objects.filter(
    Q(name__icontains=q) | Q(amount__icontains=q) | Q(category__icontains=q)
)

I'm not sure about the type of amount and category in your model so icontains may not work on them.

see this link.

这篇关于如何获得多个字段与django过滤器图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆