[Answer]-Django – for-loop with variable field name

1👍

You need to use strings:

image_list = ['image_1', 'image_2', 'image_3', 'image_4', 'image_5']

# or doing that dynamically as well:
image_list = ['image_%d' % i for i in xrange(1,6)]

Also, from your example, I am not sure where you are getting a unique pk value each time. But assume each loop should produce a different details object to compare to that specific image.

One thing to consider is that you should almost never do a blanket try, except: pass. It can easily mask errors that you didn’t consider:

try:
    details = Model.objects.get(pk=pk)
    ...
# django models have a special exception type
# when they don't exist.
except Model.DoesNotExist: 
    pass 

In order to dynamically use those string names as variable lookups, you just need to use getattr

for image_name in image_list:
    ...
    # equiv to: details.image_1, details.image_2, ...
    if getattr(details, image_name, None) != form_image:
    ...
👤jdi

Leave a comment