[Fixed]-Django/python How to get a list of id's from a list of Objects

34👍

If the return value of the friends method is a QuerySet object, you can use QuerySet.values_list method:

friends_ids = friends.values_list('id', flat=True)

If it’s not a QuerySet object, you can use list comprehension (This one can be used for both QuerySet and non-QuerySet one):

friends_ids = [friend.id for friend in friends]

Leave a comment