1

I'm using django ORM's exact() method to query only selected fields from a set of models to save RAM. I can't use defer() or only() due to some constraints on the ORM manager I am using (it's not the default one).

The following code works without an error:

 q1 = Model.custom_manager.all().extra(select={'field1':'field1'})
 # I only want one field from this model

However, when I jsonify the q1 queryset, I get every single field of the model.. so extra() must not have worked, or am I doing something wrong?

print SafeString(serializers.serialize('json', q1))
>>> '{ everything!!!!!}'

To be more specific, the custom manager I am using is django-sphinx. Model.search.query(...) for example.

Thanks.

Lucas Ou-Yang
  • 5,505
  • 13
  • 43
  • 62

1 Answers1

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.

mgrouchy
  • 1,971
  • 1
  • 12
  • 9