2013-03-18 20 views
0

我想一些額外的信息添加到一個目標在我看來建模:無法添加額外的信息,鑑於

photos = gallery.photos 
    for p in photos: 
     try: 
      extra_info = SomethingElse.objects.filter(photo=p)[0] 
      p.overlay = extra_info.image 
      logger.debug(p.overlay.url) 
     except: 
      logger.debug('overlay not found') 
      p.overlay = None 

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

記錄器輸出我希望看到的網址。在我的模板中,我只有:

<img src='{{ photo.overlay.url }}' alt='' /> 

for循環內。照片本身顯示得很好,但沒有疊加。

我在做什麼錯?我應該如何將這些額外的信息添加到對象?

回答

1

我猜照片是一個查詢集。當你遍歷它時,django將返回代表你的數據的python對象,當你做p.overlay = extra_info.image時,你只是修改這個python對象,而不是queryset。在循環結束時,並且由於queryset結果由django緩存,所以您的本地修改已消失。

我建議的是傳遞給你的模板的字典列表,而不是查詢集。喜歡的東西:

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)) 

應該無需任何修改工作,你的模板:)

UPDATE: 我想一個其他的解決辦法,也許更優雅,肯定更有效:添加覆蓋()函數你類模型:

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 

這裏你不需要做什麼特別在你看來,也不在你的模板!

+0

第二個答案很好,這就是我應該做的。謝謝! – fredley 2013-03-18 12:59:48