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.
Asked
Active
Viewed 964 times
1

Avishkar Yonjan Tamang
- 97
- 1
- 13
2 Answers
2
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.

Willem Van Onsem
- 443,496
- 30
- 428
- 555
-
Thank you. Yup using the distinct would have method the queryset without the duplicates. – Avishkar Yonjan Tamang Mar 22 '22 at 20:00
0
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.

Josh
- 280
- 2
- 13
-
You can not make a set of lists since lists are mutable, you should work with tuples instead. – Willem Van Onsem Mar 13 '22 at 07:51
-
Whoops, you're right! And your answer is clearly the better answer. Thanks for pointing that out – Josh Mar 13 '22 at 12:32