Home > database >  how to convert a QuerySet to a set in django?
how to convert a QuerySet to a set in django?

Time:03-13

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related