how to convert a QuerySet to a set in django?

1.1k Views Asked by At

I have a query, name_phonenum = person.objects.value_list('first_name','phone_num') I want to convert the queryset to a set. Any idea how can do it.

2

There are 2 best solutions below

1
On BEST ANSWER

You can wrap it over a set(…):

set(person.objects.value_list('first_name','phone_num'))

But you can let the database do the work with the .distinct(…) method [Django-doc]:

person.objects.value_list('first_name','phone_num').distinct()

this will minimize the bandwidth from the database to the application layer.

2
On
people = Person.objects.all()
people_list = []
for person in people:
    people_list.append([person.first_name, person.phone_num])

people_set = set(people_list)

Didn't test this in shell, but should work fine.

Edit: William is correct, and his answer is much better.