'how to convert a QuerySet to a set in django?
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.
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Willem Van Onsem |
| Solution 2 |
