djangodjango-queryset

How to convert a Django QuerySet to a list?


I have the following:

answers = Answer.objects.filter(id__in=[answer.id for answer in answer_set.answers.all()])

then later:

for i in range(len(answers)):
    # iterate through all existing QuestionAnswer objects
    for existing_question_answer in existing_question_answers:
        # if an answer is already associated, remove it from the
        # list of answers to save
        if answers[i].id == existing_question_answer.answer.id:
            answers.remove(answers[i])           # doesn't work
            existing_question_answers.remove(existing_question_answer)

I get an error:

'QuerySet' object has no attribute 'remove'

I've tried all sorts to convert the QuerySet to a standard set or list. Nothing works.

How can I remove an item from the QuerySet so it doesn't delete it from the database, and doesn't return a new QuerySet (since it's in a loop that won't work)?


Solution

  • You could do this:

    import itertools
    
    ids = set(existing_answer.answer.id for existing_answer in existing_question_answers)
    answers = itertools.ifilter(lambda x: x.id not in ids, answers)
    

    Read when QuerySets are evaluated and note that it is not good to load the whole result into memory (e.g. via list()).

    Reference: itertools.ifilter

    Update with regard to the comment:

    There are various ways to do this. One (which is probably not the best one in terms of memory and time) is to do exactly the same :

    answer_ids = set(answer.id for answer in answers)
    existing_question_answers = filter(lambda x: x.answer.id not in answers_id, existing_question_answers)