[patch] Allow selecting individual fields in SQL SELECT statements via the models API
|Reported by:||rmunn@…||Owned by:||adrian|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
A common request on IRC recently has been "How do I do SELECT DISTINCT field FROM table"? The models API currently doesn't have any way to allow this: it will only do the equivalent of SELECT *.
After discussing this on the django-developers list (http://groups-beta.google.com/group/django-developers/browse_thread/thread/488194de26e0ce18/), I've written a patch to add two functions to the models API at the module level: get_values() and get_values_iterator(). They act exactly like the get_list() and get_iterator() functions, but instead of returning a list (or iterator) of model API objects, they return a list (or iterator) of dictionaries. They also allow a new keyword parameter, "fields", which is a list (or tuple) of field names to return from the SELECT.
Thus, with the following patch, doing "SELECT DISTINCT year, month FROM blog ORDER BY year ASC, month ASC" would be written "results = blog.get_values(fields=['year','month'], order_by=['year','month'], distinct=True)".