简体   繁体   中英

Django if elif else statement

I'm trying to print the result according to the user's age selection in the form, but my if,elif and else statements are not working.

class Quiz(models.Model):
    age_choices = (('10-12', '10-12'),
        ('13-16', '13-16'), 
        ('17-20', '17-20'),
        ('21-23','21-23'),
        )   
   age = models.CharField(max_length = 100, choices = age_choices)
views.py
def create_order(request):
  form = QuizForm(request.POST or None)
  if request.method == 'POST':
     quiz = Quiz.objects
     if quiz.age=='10-12':
        print("10-12")
     elif quiz.age=='13-16':
        print("13-16")
     elif quiz.age=='17-20':
        print("17-20")
     elif quiz.age=='21-23':
        print("21-23")
     else:
         return None
   context = {'form':form}

   return render(request, "manualupload.html", context)
    
   
     

quiz = Quiz.objects will return a django.db.models.manager.Manager object and this can be further used to fetch the objects from database belonging to that particular model. The appropriate query set will be quiz = Quiz.objects.all() Then you will get the list of all objects in that belong to Quiz model. Once you get list of all objects, you can get the specific object either by indexing or by filtering using a specific query that you need to look into and then for that particular object you can get the age property.

Refer to official django documentation about creating queries for more information.

As @Abhijeetk431 mentioned, your issue lies in quiz = Quiz.objects .

If you use type(quiz) , you will find that it outputs django.db.models.manager.Manager . This is not what you want, as age is a property of the Quiz class, not the Manager class.

For starters, refer to this .

This will return you a Queryset list , something akin to an Excel table. age is akin to the column in the table. To get age , what you want is the row (the actual Quiz object) in said table, which you can achieve using get or using the square brackets [] .

Thus, your code should look something like this:

Model.objects.all()[0]

That would return the correct object(only the first row) and allow you to get the column value.

However, further clarification will be needed though, to know exactly what your problem is aside from 'it doesnt work'. How did you know your code is not working; what did the debugger tell you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM