[Answer]-Can't add extra information to model in view

1πŸ‘

βœ…

I guess photos is a queryset. When you iterate over it django will return python objects reprsenting your data and when you do p.overlay = extra_info.image you are just modifying this python object, not the queryset. At the end of your loop, and because queryset results are cached by django, your local modifications are gone.

What I’d suggest is to pass to your template a list of dictionaries instead of a queryset. Something like:

photos = gallery.photos
photo_list = []
for p in photos:
    new_photo = {}
    new_photo['url'] = p.url
    # [...] copy any other field you need
    try:
        extra_info = SomethingElse.objects.filter(photo=p)[0]
        new_photo['overlay'] = extra_info.image
    except:
        logger.debug('overlay not found')
        new_photo['overlay'] = None
   photo_list.append(new_photo)

return render_to_response('account/site.html',
                      {'photos': photo_list},
                      context_instance=RequestContext(request))

should work without any modification to your template πŸ™‚

UPDATE:
I’m thinking of an other solution, maybe more elegant and for sure more effective: add an overlay() function to you class Model :

class Photo(models.Model):
  [...]

  def overlay(self)
    try:
      extra_info = SomethingElse.objects.filter(photo=self)[0]
      return extra_info.image
    except:
      logger.debug('overlay not found')
      return None

here you don’t need to do anything special in your view, nor in your template!

πŸ‘€Ponytech

Leave a comment