Django REST structure, get object from url

I am wondering if there is a clean way to get an object from its URL using the django rest framework. Of course, it should be, since this is similar to what happens when used HyperlinkedRelatedField.

For example, I have this URL /api/comment/26as a string. From my point of view, how can I get a comment instance using pk=26?

Of course, I could redo the work and work on the string, but should this be the best way?

Many thanks.

EDIT:

Here is how I solved it at the end:

resolve('/api/comment/26/').func.cls.modelwill return my comment on the model. resolve('/api/category/1/').kwargs['pk']will return pk.

What gives you:

from django.core.urlresolvers import resolve

resolved_func, unused_args, resolved_kwargs = resolve('/api/category/1/')
resolved_func.cls.model.objects.get(pk=resolved_kwargs['pk'])
+4
source share
3 answers

, url - URLConf.

, resolve.

ResolverMatch, func, as_view URL-.

__name__ . - globals()[class_name], .

model.

, . , URL- .

+3

:

resolve(url).func.cls.serializer_class.Meta.model.objects.get(
    **resolve(url).kwargs)
+1

The solution above did not work for me, however the following:

from django.core.urlresolvers import resolve

resolved_func, unused_args, resolved_kwargs = resolve('/api/category/1/')
resolved_func.cls().get_queryset().get(id=resolved_kwargs['pk'])

In addition, this solution uses a built-in set of queries of your kind, which may contain annotations or important filters.

Using HyperlinkedModelSerializer I really needed to do this with the full url. To do this, you first need to extract the path, resulting in:

import urllib.parse
from django.core.urlresolvers import resolve

def obj_from_url(url):
    path = urllib.parse.urlparse(url).path
    resolved_func, unused_args, resolved_kwargs = resolve(path)
    return resolved_func.cls().get_queryset().get(id=resolved_kwargs['pk'])
0
source

Source: https://habr.com/ru/post/1524074/


All Articles