Django Pagination - redirect to the page the object is on

I am working on an image portfolio app and I have a url that looks like this:

url(r'^(?P<slug_val>[-\w]+)/(?P<page>[0-9]+)/(?P<id>[0-9]+)/$', 'portfolio.views.imagedetail')

      

Essentially the element page

is only there, so I can nicely redirect the user back to the thumbnail page they came from. However, if the URL is passed and then some images are added or removed in front of the image, then it may no longer be on this page. I would like to redirect users in this case:

slug/correctpage/id

      

What I can't seem to get it working is how to determine which page the image is on using Django's inline pagination. Here's what I have so far:

def imagedetail(request, slug_val, page, id):
    p = get_object_or_404(MyPortfolio, slug=slug_val)

    paginator = Paginator(p.images.all(), 25)

    # find out which page the image with id is on, if it not page,
    # then redirect, otherwise render

      

I know I could iterate over each page, but it looks like it will hit the database without issue, and I'm sure there must be a more elegant way to do this.

Thanks,

House

0


a source to share


1 answer


If you want to take database changes into account, you have no choice but to query the database or ... you must cache the changes in memory somewhere if you are using only one web server. The latter option is only an option if you have too much data or enough memory available.

The most elegant way to query is something like the following, but this is very difficult to achieve in Django 1.0 without using SQL:

SELECT COUNT(*) + 1 FROM images WHERE images.field < currentfield 

      



(where field is the field of the field you are using to order your images)

To use raw SQL in Django, you can read this page for more information.

Then you know the position of your image and you can easily calculate the page the element is in.

+2


a source







All Articles