I have been struggling with this for hours, I have a variable :
numbered_objects = [(index + 1, obj) for index, obj in enumerate(carts)]
that makes me a list like this from my Model :
[(1, <CalculatedNumbers: one>), (2, <CalculatedNumbers: two>), (3, <CalculatedNumbers: three>), (4, <CalculatedNumbers: four>), ...]
and I have another variable : 'usernobat' that returns me a number
How can I go through my list of tupples, find the matching tupple index that is matching 'usernobat' and return its data ?
I have tried for loops like this :
matching_object = None
for obj in range(len(numbered_objects)):
for key in numbered_objects[obj]:
if key == usernobat:
matching_object = key
break
but they all return None
edit: I added my entire view :
def cart_resault(request):
carts = CalculatedNumbers.objects.filter(used=False)[:50]
usersubmit = UserSelection.objects.get(user=request.user)
usernobat, usernobat__created = UserNobats.objects.get_or_create(user=request.user)
numbers_sum = sum(getattr(usersubmit, f'number_{i}', 0) for i in range(1, 11))
usernobat.usernobat = numbers_sum
usernobat.save()
numbered_objects = [(index + 1, obj) for index, obj in enumerate(carts)]
matching_object = None
for obj in range(len(numbered_objects)):
for key in numbered_objects[obj]:
if key == usernobat:
matching_object = key
break
I think your usernobat
is probably still a string, so '2'
for example, not 2
, and thus 2 != '2'
.
You can cast it to a 2
with int(…)
first, so:
usernobat = int(usernobat)
matching_object = None
for k, v in numbered_objects:
if k == usernobat:
matching_object = v
break