I have a model Foo which have a ForeignKey to the User model.
Later, I need to grab all the User’s id and put then on a list
foos = Foo.objects.filter(...) l = [ f.user.id for f in foos ]
But when I do that, django grabs the whole User instance from the DB instead of giving me just the numeric user’s id, which exist in each Foo row.
How can I get all the ids without querying each user or using a select_related?
Thanks
Use queryset’s values() function, which will return a list of dictionaries containing name/value pairs for each attribute passed as parameters:
The ORM will then be able to optimize the SQL query to only return the required fields, instead of doing a ‘SELECT *’.