我有一個函數在我的類Image
中的對象的id
中傳遞。我需要模型中下一個對象的id
。目前,我正在儘可能以最低效率的方式做到這一點,因爲我需要讓所有對象都這樣做。我目前的實現是:在Django模型中獲取下一個對象的ID
def get_next_id(curr_id):
result = []
Image_list = Image.objects.all()
total = Image.objects.all().count()
for i 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
return Image_list[new_index]
我將不勝感激,如果有人可以提供一個更好的方法,或使這種方法更有效。謝謝。
這樣的事情? 'DEF get_next_id(curr_id): 嘗試: next_image = Image.objects.get(PK = curr_id + 1) 返回next_image 除了DoesNotExist: 返回Image.objects.get(PK = 0)的'ps。我沒有測試過它。 – 2014-10-22 09:39:03
這味道像[XY問題](http://meta.stackexchange.com/q/66377/241526)。解釋導致您需要圖像的下一個ID的問題。 – Louis 2014-10-22 09:46:39
@limelights我不能這樣做,因爲我刪除了ID,所以下一個ID可能並不總是舊的ID + 1. – user4052205 2014-10-22 10:10:45