Reputation: 3756
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.
Upvotes: 10
Views: 27195
Reputation: 6933
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"
Upvotes: 17
Reputation: 1220
Modern way to do this in django >1.9:
[f.get_attname() for f in Restaurant._meta.fields]
Upvotes: 10