1

I have to filter data from model based on the run time values. I am getting 5 values via query string. My querystring is like below:

http://127.0.0.1:8000/personal/search/?month=&year=&account=&deliveryManagedFrom=&marketmName=

So, I want to include all or none of the values in the filter so that it displays the desired result. Below is the filter query which I am writing:

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']

It is working well in case, all the values have been provided.

In case, if any value is blank, it should not consider that value and display output as per other filter criteria.

Pls suggest how to implement an OR filter with 5 data inputs. It is not necessary that all 5 data inputs have values . So the value can be None or the value in the querystring

3 Answers 3

3

Filter the request for non-empty values and then use dictionary expansion to do the query.

q =  {k:v for k, v in request.GET.items() if v}
sum_tt_count = NetworkRelatedInformation.objects.filter(**q).aggregate(Sum('tt_count'))
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! It is awesome and generic which can be used for any number of values in the querystring.
HI Daniel... Can you Pls look on my other question stackoverflow.com/questions/51202612/… I tried multiple ways using filter method, @ property and qs but nothing is working for me.. Pls see if you can support on this
2

You can do it using 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'))

Comments

0

For handling the None values i have to explicitly write the below code.

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.