我必须根据运行时值从模型中筛选数据。我正在通过查询字符串获得5个值。我的查询如下:
http://127.0.0.1:8000/personal/search/?month=&year=&account=&deliveryManagedFrom=&marketmName=因此,我希望在筛选器中包含所有或任何一个值,以便它显示所需的结果。下面是我正在编写的筛选器查询:
sum_tt_count = NetworkRelatedInformation.objects.filter(month=month, year=year, account_id=account, account__deliveryManagedFrom=deliveryManagedFrom, account__marketName=market).aggregate(Sum('tt_count'))
totalttcount = sum_tt_count['tt_count__sum']它工作得很好,以防所有的价值都被提供了。
如果任何值为空,则不应考虑该值并按照其他筛选条件显示输出。
请建议如何实现具有5个数据输入的OR过滤器。不需要所有5个数据输入都有值。因此,该值可以是空值,也可以是querystring中的值。
发布于 2018-07-08 08:54:57
过滤非空值的请求,然后使用字典展开来执行查询.
q = {k:v for k, v in request.GET.items() if v}
sum_tt_count = NetworkRelatedInformation.objects.filter(**q).aggregate(Sum('tt_count'))发布于 2018-07-08 08:29:47
你可以用Q object来做
from django.db.models import Q
NetworkRelatedInformation.objects.filter(Q(month__isnull=True) | Q(month=month), Q(year__isnull=True) | Q(year=year)).aggregate(Sum('tt_count'))发布于 2018-07-08 09:16:13
为了处理无值,我必须显式地编写以下代码。
account = request.GET.get('account')
if account is '':
account = None
month = request.GET.get('month')
if month is '':
month = None
year = request.GET.get('year')
if year is '':
year = None
sum_alarm_count = NetworkRelatedInformation.objects.filter(Q(month=month) | Q(year=year) | Q(account_id=account)) \
.aggregate(Sum('alarm_count'))
totalalarmcount = sum_alarm_count['alarm_count__sum']https://stackoverflow.com/questions/51230090
复制相似问题