Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get model object from tastypie uri?

How do you get the model object of a tastypie modelresource from it's uri?

for example:

if you were given the uri as a string in python, how do you get the model object of that string?

like image 816
Derek Avatar asked May 02 '13 05:05

Derek


1 Answers

Tastypie's Resource class (which is the guy ModelResource is subclassing ) provides a method get_via_uri(uri, request). Be aware that his calls through to apply_authorization_limits(request, object_list) so if you don't receive the desired result make sure to edit your request in such a way that it passes your authorisation.

A bad alternative would be using a regex to extract the id from your url and then use it to filter through the list of all objects. That was my dirty hack until I got get_via_uri working and I do NOT recommend using this. ;)

id_regex = re.compile("/(\d+)/$")
object_id = id_regex.findall(your_url)[0]
your_object = filter(lambda x: x.id == int(object_id),YourResource().get_object_list(request))[0]
like image 185
Zakum Avatar answered Sep 26 '22 17:09

Zakum