Query grouped data in django
I'm trying to optimize my very simple pagination system. I'm fetching a specific content from my models with
myModel.objects.get(slug='my slug bla bla bla')
and I'开发者_开发知识库d like to be able to get in same request, the next and preceding Pk from my id, in order to display a next/prec button based on the Pk or posted. I've taken a look at pagination, but didn't found how to solve my prec = slug-pk - 1, slug, next = slug-pk + 1 with it. At the moment i've added to fields in my model in order to fetch the next and prec absolute urls, but It's quite ugly and makes a lot of useless SQL queries. You can take a look at the output here: http://diasporamas.com/le-barbier-de-paris/watch
Any ideas on how to improve my fetching?
Thank you!
I don't believe that it's possible to do that in one query.
The most efficient way I can think of would be:
current = myModel.objects.get(slug='my slug bla bla bla')
next = None
next_pk = current.pk + 1
previous = None
prev_pk = current.pk - 1
for mod in myModel.objects.filter(pk__in=(next_pk, prev_pk)):
if mod.pk == next_pk:
next = mod
else:
prev = mod
精彩评论