Get model object from tastypie uri?

How do you get a tastypie modelresource model object from it uri?

eg:

if you got uri as a string in python, how do you get the model object of this string?

+5
source share
3 answers

The Tastypie resource class (which is the ModelResource guy is a subclass) provides a method get_via_uri(uri, request). Keep in mind that his calls are up to apply_authorization_limits(request, object_list), so if you do not get the desired result, be sure to edit your request so that it passes authorization.

A bad alternative is to use a regular expression to extract the identifier from your URL, and then use it to filter by the list of all objects. It was my dirty hack until I got a get_via_uri job 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]
+2
source

get_via_uri, , @Zakum, , , , . , , , URI :

from django.core.urlresolvers import resolve, get_script_prefix

def get_pk_from_uri(uri):
    prefix = get_script_prefix()
    chomped_uri = uri

    if prefix and chomped_uri.startswith(prefix):
        chomped_uri = chomped_uri[len(prefix)-1:]

    try:
        view, args, kwargs = resolve(chomped_uri)
    except Resolver404:
        raise NotFound("The URL provided '%s' was not a link to a valid resource." % uri)

    return kwargs['pk']

Django - (.. get_script_prefix() == '/'), :

view, args, kwargs = resolve(uri)
pk = kwargs['pk']
+2

Are you looking for a flow chart ? It really depends on when you want the object.

During the dehydration cycle, you can access it through a bundle, for example.

class MyResource(Resource):
    # fields etc.

    def dehydrate(self, bundle):
        # Include the request IP in the bundle if the object has an attribute value
        if bundle.obj.user:
            bundle.data['request_ip'] = bundle.request.META.get('REMOTE_ADDR')
        return bundle

If you want to manually get the object by api url, the given template, can you just pass the slug or primary key (or something else) through the default orm scheme?

+1
source

All Articles