Abjilla22
Abjilla22

Reputation: 11

How to extract values from queryset objects in python?

I'm trying to compare values to each other for a quiz in django. I'm using POST data for object data and trying to compare each other.

Current code:

answerList = []
answerList2 = []
for i in Question.objects.filter(related_quiz = examid):
    answerList.append(i.answer)

form = EditQuizForm()
form = EditQuizForm(request.POST)

if request.method == "POST":
    form = EditQuizForm(request.POST)
    submittedObject = request.POST.copy()
    newList = (dict(submittedObject.lists()))
    values = newList.values()
    for i in values:
        answerList2.append(i)

    print(answerList)
    print(answerList2)

This returns the values:

      ['A', 'D']
      [['A'], ['D']]

However, I cannot iterate over these to compare them as they are not the same. I do not how get answerList2 to appear like answerList1 so i can compare the values. Any help would be appreciated as i am fairly new to python/django.

Upvotes: 0

Views: 2866

Answers (1)

GeekSilva
GeekSilva

Reputation: 571

You can loop and compare the values of answerList with the value of index 0 of answerList2

def compareLists(answerList, answerList2):
   for i in range(len(answerList)):
      if answerList[i] != answerList2[i][0]:
         break
   else:
      return True
   return False

When an item is different the loop will be broken with break and the function will return False. Otherwise it will not exit with break and return True.

I hope I have helped :)

Upvotes: 1

Related Questions