Saturday 15 January 2011

Get id of next object in Django model -



Get id of next object in Django model -

i have function passed in id of object in class image. need id of next object in model. currently, doing in to the lowest degree efficient way possible need objects this. current implementation is:

def get_next_id(curr_id): result = [] image_list = image.objects.all() total = image.objects.all().count() in range(len(image_list)): result.append(image_list[i].id) index_curr = result.index(curr_id) if index_curr == total: new_index = 0 else: new_index = index_curr + 1 homecoming image_list[new_index]

i grateful if provide improve way, or create 1 more efficient. give thanks you.

i suggest this:

def get_next_id(curr_id): try: ret = image.objects.filter(id__gt=curr_id).order_by("id")[0:1].get().id except image.doesnotexist: ret = image.objects.aggregate(min("id"))['id__min'] homecoming ret

this not take care of special case table empty, should not have valid curr_id in first place if table empty. not protect against passing nonsensical values curr_id.

what first id greater current one. [0:1] piece limits info returned database first record: in effect database performing piece rather python. if there no id greater current one, lowest one.

in response comment how in reverse:

def get_prev_id(curr_id): try: ret = image.objects.filter(id__lt=curr_id).order_by("-id")[0:1].get().id except image.doesnotexist: ret = image.objects.aggregate(max("id"))['id__max'] homecoming ret

the changes are:

use id__lt, , order -id.

use max rather min aggregate, , utilize id__max key rather id__min value.

django django-models

No comments:

Post a Comment