qs = MyModel.objects.only('id', 'name')
select = qs.query.select #should be ['id','name']
You may be looking for values.
MyModel.objects.all().values()
returns a QuerySet list of dictionaries with the field names as the keys.
You can specify which specific fields you want to return by passing them as arguments to values().
MyModel.objects.all().values('id', 'name')
Then you can use the first item in the QuerySet to retrieve all the keys.
MyModel.objects.all().values('id', 'name')[0].keys()
https://docs.djangoproject.com/en/1.11/ref/models/querysets/#values
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
django-users...@googlegroups.com.
To post to this group, send email to
django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/56059101-4006-4ab4-91dd-3a696e07f101%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Take a look at `values_list` too.
1) Dict keys are unordered, I would prefer to be ordered as requested (or as defined in the Model) I guess with some help from _meta.fields I can partially solve this)
2) . values() changes the queryset, I'm not sure if this won't have some side effects of the final result?
3) The whole approach of evaluating the queryset + picking the first item is just looking hacky. But as I already said If there is nothing better I will go for it.
Imagine you have a queryset you know nothing about it (how it gets generated) and you want to build a representation (table) of it. The first thing would be to render the table header, to do so you need to know what fields are selected + their order.