[Answer]-Return the result of a method in a QuerySet.values() or values_list()?

1👍

You might want to try using only() instead of values(). Like values() it will only fetch the specified fields from the database, but unlike values() it will return actual instance objects that you can call methods on.

That way, whether you’re looping in the view or the template, you can access the method in addition to the specified fields.

If you need dictionary-like structures (for json.dumps(), say) you can just construct them in a comprehension:

instances = MyModel.objects.only('name')
data = [{'name': instance.name, 
         'favourite': instance.favouriteNumber()} for instance in instances]

Leave a comment