I have done some digging into the QuerySet API, and I think I may have found 
what you are looking for:
MyModel.objects.all().query.get_meta().fields

You can access the fields that are deferred by using 
MyModel.objects.all().query.deferred_loading.  Note that the deferred columns 
will still be retrieved from the database when requested.  

You can also access annotations by using 
MyModel.objects.all().query.annotations, which is an OrderedDict.

In short, it doesn't look like there is an easy to way to simply access all the 
fields that are going to appear in your SELECT clause of your query from the 
query itself.  You will need to process them.

And, you're right; selecting the first item in a queryset does seem hackish.  
You could even try this:
MyModel.objects.values().first()
which will return None if the queryset is empty, which doesn't have an 
attribute of .keys().


-----Original Message-----
From: django-users@googlegroups.com [mailto:django-users@googlegroups.com] On 
Behalf Of Todor Velichkov
Sent: Thursday, June 15, 2017 12:36 PM
To: Django users
Subject: RE: How to get a list of queryset selected fields

Hello, Matthew Pava, thank you for your answer. 
This is probably the solution which I'm going to use if there isn't anything 
better, but overall I don't like this approach for a few reasons: 

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.

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@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/7d3ecf53-ccad-4620-b34b-48c1788dba6a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@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/70c90ae869f9455c8f483479fa2e0c9d%40ISS1.ISS.LOCAL.
For more options, visit https://groups.google.com/d/optout.

Reply via email to