Проверьте, что это 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])
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.
Предположим в целях иллюстрации, что ваши модели являются стандартными с первичным ключом id
, тогда оценка
list(qs.values_list('id', flat=True)).index(obj.id)
найдет индекс obj
в qs
. Хотя использование list
оценивает набор запросов, оно оценивает не исходный набор запросов, а производный набор запросов. Эта оценка запускает SQL-запрос, чтобы получить только поля идентификатора, не тратя время на выборку других полей.
Компактный и, вероятно, наиболее эффективный:
for index, item in enumerate(your_queryset):
...