Получите индекс элемента в queryset

Проверьте, что это Swift 4

let myString = "LOVE"

self.textField1.text = String(Array(myString)[0])
self.textField2.text = String(Array(myString)[1])
self.textField3.text = String(Array(myString)[2])
self.textField4.text = String(Array(myString)[3])
37
задан Ian Elliott 14 July 2009 в 02:02
поделиться

3 ответа

QuerySets in Django are actually generators, not lists (for further details, see Django documentation on QuerySets).
As such, there is no shortcut to get the index of an element, and I think a plain iteration is the best way to do it.

For starter, I would implement your requirement in the simplest way possible (like iterating); if you really have performance issues, then I would use some different approach, like building a queryset with a smaller amount of fields, or whatever.
In any case, the idea is to leave such tricks as late as possible, when you definitely knows you need them.
Update: You may want to use directly some SQL statement to get the rownumber (something lie . However, Django's ORM does not support this natively and you have to use a raw SQL query (see documentation). I think this could be the best option, but again - only if you really see a real performance issue.

16
ответ дан 27 November 2019 в 04:06
поделиться

Предположим в целях иллюстрации, что ваши модели являются стандартными с первичным ключом id , тогда оценка

list(qs.values_list('id', flat=True)).index(obj.id)

найдет индекс obj в qs . Хотя использование list оценивает набор запросов, оно оценивает не исходный набор запросов, а производный набор запросов. Эта оценка запускает SQL-запрос, чтобы получить только поля идентификатора, не тратя время на выборку других полей.

12
ответ дан 27 November 2019 в 04:06
поделиться

Компактный и, вероятно, наиболее эффективный:

for index, item in enumerate(your_queryset):
    ...
59
ответ дан 27 November 2019 в 04:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: