Skip to content

Instantly share code, notes, and snippets.

@stevekane
Created January 19, 2013 06:20
Show Gist options
  • Save stevekane/4571027 to your computer and use it in GitHub Desktop.
Save stevekane/4571027 to your computer and use it in GitHub Desktop.
A brief discussion of views that parse request.QUERY_PARAMS and convert them into a query that is run against the database
I am looking for a library that handles request.QUERY_PARAMS and converts the parameters into a database query that returns a queryset.
The pattern I am using arrises from Ember.js 's wish to be able to send queries of the following format to my back-end and have it return the desired queryset:
GET Request: http://myurl.com/api/modelname?attribute=value
where attribute is a property of the model and value is the targetted value
in the trivial case, it should be able to generate a query such as:
model.object.get(attribute = value)
however there are many exceptional cases that must be handled such as:
GET Request: http://myurl.com/api/modelname?attribute=val1, val2, val3 or
GET Request: http://myurl.com/api/modelname?attribute=val1, val2, null
I have created a hack that handles these by parsing QUERY_PARAMS and digging through it to construct queries for attributes that may be numbers or null. The essential excerpt from that hack is listed below.
The method finds the queryset then uses string.split on commas to create a list of queried values
I then construct two dictionaries; one for "attribute__in" and one for "attribute__isnull"
Q objects are used to create the needed query agaisnt my db.
def get_integer_queryset(self, query, queryset):
query_key = str(query.keys()[0])
query_values = query.get(query_key, None).split(",")
query_vals_no_null = {query_key+"__in": []}
optional_null_dict = {}
for value in query_values:
if value == "null" or value == "None":
optional_null_dict[query_key+"__isnull"] = True
else:
query_vals_no_null[query_key+"__in"].append(value)
return queryset.filter( Q(**query_vals_no_null) |
Q(**optional_null_dict) )
This method does work for queries agaisnt objects that have numerical values and it handles the special case of null correctly.
My question is, is there a better way to do this or a library that has already done this? I see this as being a pretty essential feature of the modern REST-ful api so I was surprised to have such difficulty in finding it.
Thanks very much in advance,
Steve Kane
@tomchristie
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment