[Answered ]-Django Query only one field of a model using .extra() and without using .defer() or .only()

2👍

So, Im not sure if you can do exactly what you want to do. However, if you only want the values for a particular field or a few fields, you can do it with values

It likely does the full query, but the result will only have the values you want. Using your example:

q1 = Model.custom_manager.values('field1', 'field2').all()

This should return a ValuesQuerySet. Which you will not be able to use with serializers.serialize so you will have to do something like this:

from django.utils import simplejson
data = [value for value in q1]
json_dump = simplejson.dumps(data)

Another probably better solution is to just do your query like originally intended, forgetting extra and values and just use the fields kwarg in the serialize method like this:

print SafeString(serializers.serialize('json', q1, fields=('field1', 'field2')))

The downside is that none of these things actually do the same thing as Defer or Only(all the fields are returned from the database), but you get the output you desire.

Leave a comment