Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: get all columns as a list

Tags:

django

This is probably very simple, but I just can't figure out how to do it.

I want to get all the columns in some rows as a list. I know I could use values_list and flat=True and list all the columns, but is that the only way?

I want to do something like this:

rows = FOO.objects.filter(bar='baz')

and get a list of lists instead a list of FOO objects.

like image 214
Larry Martell Avatar asked May 19 '16 23:05

Larry Martell


1 Answers

You can get the name of all fields this way:

model._meta.get_all_field_names()

or

[field.name for field in model._meta.get_fields()]  # for Django >= 1.9

therefore, you can do something like:

FOO.objects.filter(<your filter>).values_list( * FOO._meta.get_all_field_names(), flat=True)

If you don't want to pass the field names then you can do:

FOO.objects.values_list()

You can see in the reference: "If you don’t pass any values to values_list(), it will return all the fields in the model, in the order they were declared"

Edit

The referenced link is no longer available. It may be seen on docs.

like image 146
trinchet Avatar answered Sep 23 '22 06:09

trinchet