gur
gur

Reputation: 37

django query not matching

my query is not working properly. when i select the male part and then age_from to age_to and date_from to date_to its not actually select the male from my database according to my query .actually according to my database male record between age 5 to age 15 and date 2011-04-05 to 2011-05-05 is only 1 but it showing 3 records.

this is my query: as follows patient = PatientInfo.objects.filter(dateedit__range=(date_from,date_to),age__range=(age_from,age_to),gender__iexact='male')

i think there is some wrong in my query.. im nt getting exactly...

flag = 0 if request.POST.has_key('gender'): search_gender = request.POST["gender"]

    if search_gender == 'male':
        flag == 1

    if search_gender == 'female':
        flag == 2

    if search_gender == 'both':
        flag == 3

age_from = request.POST["age_from"]
age_to = request.POST["age_to"]
date_from = request.POST["date_from"]
date_to = request.POST["date_to"]

patient = PatientInfo()

if date1 and date2:
    if age1 and age2:
             if flag == 1:
                 patient = PatientInfo.objects.filter(dateedit__range=(date_from,date_to),age__range=(age_from,age_to),gender__iexact='male')
             else:
                  patient = PatientInfo.objects.filter(dateedit__range=(date_from,date_to),age__range=(age_from,age_to))
                  if flag == 2:
                      patient = PatientInfo.objects.filter(dateedit__range=(date_from,date_to),age__range=(age_from,age_to),gender__iexact='female')
                  else:
                      patient = PatientInfo.objects.filter(dateedit__range=(date_from,date_to),age__range=(age_from,age_to))
                      if flag == 3:
                          patient = PatientInfo.objects.filter(dateedit__range=(date_from,date_to),age__range=(age_from,age_to),gender__iexact='male')

Upvotes: 0

Views: 279

Answers (1)

Joe
Joe

Reputation: 47739

You can build up queries bit by bit, adding extra filters as you go. This will tidy up your logic. Also, elif is your friend. Also, next time use CHOICES for values like gender.

I have not tested this, but this is the kind of syntax you want

query = PatientInfo.objects.all()

if date1 and date2:
    query = query.filter(dateedit__range=(date_from,date_to))

if flag == 1:
    query = query.filter(gender__iexact='male')
elif flag == 2:
    query = query.filter(gender__iexact='female')

Then use query as normal. Realise that queries objects are different to result sets. As you add things to your query, you are only changing a query expression tree that will be turned into SQL. Only when you execute it (turn it into a list, iterating etc) does it query the db and turn into a result set. So don't be scared to refactor logic to make tweaks to the query object.

Also be aware that you're comparing a string to an int. If you want to get the integer value, you want thing = int(request.POST['thing']).

Upvotes: 1

Related Questions