How to convert a Django QuerySet to a list

django queryset to list of dicts
django queryset to list of ids
django get list of values from queryset
django-filter foreign key
django queryset limit
distinct in django filter
django range filter
django queryset get field value

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)?

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)

How do I convert a Django QuerySet into list of dicts?, Use the .values() method: >>> Blog.objects.values() [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news. yes actually i need a queryset to perform some operations since it is an object, but i got a list as above , so want to convert the resultant list to queryset – Shiva Krishna Bavandla Sep 4 '13 at 13:03

Why not just call list() on the queryset?

answers_list = list(answers)

This will also evaluate the QuerySet/run the query. You can then remove/add from that list.

Convert queryset to list in Django, Slicing a QuerySet that has been evaluated also returns a list. in distinct() for an explanation of how related model ordering can change the expected results. You need to do this if you need to supply a QuerySet to Django REST, django-graphene, paginators or any other api that requires a QuerySet. The list of objects may come from a cache or be filtered and sorted in python (not the db). We should just write something that takes a list and quacks like a QuerySet. – Chris Sattinger May 15 '17 at 10:13

It is a little hard to follow what you are really trying to do. Your first statement looks like you may be fetching the same exact QuerySet of Answer objects twice. First via answer_set.answers.all() and then again via .filter(id__in=...). Double check in the shell and see if this will give you the list of answers you are looking for:

answers = answer_set.answers.all()

Once you have that cleaned up so it is a little easier for you (and others working on the code) to read you might want to look into .exclude() and the __in field lookup.

existing_question_answers = QuestionAnswer.objects.filter(...)

new_answers = answers.exclude(question_answer__in=existing_question_answers)

The above lookup might not sync up with your model definitions but it will probably get you close enough to finish the job yourself.

If you still need to get a list of id values then you want to play with .values_list(). In your case you will probably want to add the optional flat=True.

answers.values_list('id', flat=True)

QuerySet API reference | Django documentation, How to convert a Django QuerySet to a list answers = Answer.objects.filter(id__​in=[answer.id for answer in answer_set.answers.all()]). One more thing: before Django 1.6, there was a bug with calling values_list() on a queryset ordered by an extra column. Use this : Use this : values = queryset . values ( 'ordering' , 'label' ) labels = [ value [ 'label' ] for value in values ]

By the use of slice operator with step parameter which would cause evaluation of the queryset and create a list.

list_of_answers = answers[::1]

or initially you could have done:

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

How to convert a Django QuerySet to a list, Django Queryset:value_list() This class behaves like a list. Most of the time this is enough, but if you require an actual Python list object, you  Questions: This question already has an answer here: Order a QuerySet by aggregate field value 3 answers Answers: There is no point in converting a data list back to a query. A query object never holds data; it just represents a query to the database. It would have to fetch everything again if you made

You can directly convert using the list keyword. For example:

obj=emp.objects.all()
list1=list(obj)

Using the above code you can directly convert a query set result into a list.

Here list is keyword and obj is result of query set and list1 is variable in that variable we are storing the converted result which in list.

Django Queryset:value_list() – The Cursed One, queryset = Theme.objects.filter(pk__in=[1, 2, 10]) >>> type(queryset) <class '​django.db.models.query.QuerySet'> >>> queryset [<Theme:  I´ve seen his question has been answered multiple times for django < 2.xx, but for the current version I am using (2.1) I´been unable to convert my querysets to a json format. I´ve tried serializer using the django rest framework, but so far the only use I was able to implement is to serialize a model, so when my querysets has results from

Django : Create a QuerySet from a list, preserving order, Use the .values() method: >>> Blog.objects.values() [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news. It seems like a django queryset behaves somehow like a python list. But it doesn't support list's .append() method as I know. What I want to do is like: from my_django_app.models import MyModel

[SOLVED] How do I convert a Django QuerySet into list of dicts , use all the fields. In such situations, we can query only desired fields. Django provides two ways to do this The output will be list of dictionaries. Alternatively​  You can also convert the date in queryset to string using map function. Example: Example: qs = MyModel.objects.filter(name='me').values_list('activation_date', flat=True) data = map(str, qs)

6. How to select some fields only in a queryset?, Dig into Django query sets with Caktus developer Jeff Bradberry, using the Django shell to add 'qs', to the end of the INSTALLED_APPS list. Querysets can be converted to list. But list cannot be converted to query set. I wrote a new function in django.db.models.utils package. from django.db.models.utils import list_to_queryset queryset = list_to_queryset(object_list)

Comments
  • i've added one more line to my code sample above, deleting the same entry from exising_question_answers. is it possible to use a ifilter for that too somehow?
  • I'll mark this as correct because I didn't know about filter and had forgotten about lambdas.
  • Be careful with this. When you cast this to a a list the distinct flag may become disregarded.
  • I can do it independently, but I can do it in queryset in django form. Any idea why?
  • If so, then cast to set and then back to list to get the unique ones.
  • Thanks for your answer. Unfortunately I didn't provide enough detail to show that I can't use your approach.
  • Best solution for described problem. I want add new_answers = answers.exclude(question_answer__in=existing_question_answers.values_list('id', flat=True)) @istruble
  • As far as i know, django queryset does not support negative indexing.
  • Okay Alexey. You are right here. I have updated the answer.
  • But if you do this it doesn't work: list1 = list(emp.objects.all()) which seems counter-intuitive.