简体   繁体   中英

Partial reverse url lookup in django

I'm looking for a way to efficiently do reverse url lookup on a large number of django model instances, ideally without needing to call reverse() once for each instance. My original code looked something like this:

urls = []
for foo in Foo.objects.all():
    url = django.core.urlresolvers.reverse("foo_details", kwargs={"ver": foo.version,
                                                                  "locale": foo.locale,
                                                                  "name": foo.name})
    urls.append(url)

However, since there are a large number (thousands) of Foo objects, this process took far too long. So, I faked a "partial" url lookup once, then completed the job for each instance:

base_url = django.core.urlresolvers.reverse("foo_details", kwargs={"ver": foo.version,
                                                                   "locale": foo.locale,
                                                                   "name": ""})
urls = []
for foo in Foo.objects.all():
    url = base_url + urlquote(foo.name)
    urls.append(url)

This works, and it is much faster than my first solution, but I'm now making assumptions about the form of the url, specifically that name will always appear at the very end. Also, I'd like to make use of get_absolute_url() for this, but that eliminates the possibility of doing a partial reversal of the url only once, then completing the reversal for each object.

Is this really the only way? Is there some other way that I could keep the partial reverse lookup, then complete the url for each individual object?

I usually do something along the lines of

placeholder = "__placeholder___"
base = reverse("foo_details", 
               kwargs={"ver": foo.version,
                       "locale": foo.locale,
                       "name": placeholder})
# ...
url = base.replace(placeholder, foo.name)

which works around the assumption that the name is the last path component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM