Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load column from Database into list

Tags:

django

How do you load a database column into a list with Django? I have a 'name' column of various names in my database and I want to be able to load all those names (ordered by id) into a list. So that I can iterate over that list and print the names, like this:

for name in name_list:
      print name

I've googled this pretty thoroughly and I can't find anything. This should be so simple, its just the equivalent of SQL's "SELECT column FROM table"

class chat_messages(models.Model):
    name = models.CharField(max_length=32)
like image 896
python566 Avatar asked Jul 11 '11 16:07

python566


1 Answers

Check out the docs for values_list(). Django does a great job of creating the query specific to your request.

chat_messages.objects.all().values_list('name')

Will generate a query similar to:

SELECT `projectname_chat_messages`.`name` FROM `projectname_chat_messages`
like image 164
Jack M. Avatar answered Oct 02 '22 20:10

Jack M.