Python Can';t向视图中的模型添加额外信息
我正在尝试向视图中的对象添加一些额外信息:Python Can';t向视图中的模型添加额外信息,python,django,django-views,Python,Django,Django Views,我正在尝试向视图中的对象添加一些额外信息: 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:
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))
记录器输出我希望看到的URL。在我的模板中,我只有:
<img src='{{ photo.overlay.url }}' alt='' />
在for
循环中。照片本身显示得很好,但覆盖层显示不出来
我做错了什么?如何将这些额外信息添加到对象中?我想照片是一个查询集。当您迭代它时,django将返回代表您的数据的python对象,而当您执行p.overlay=extra_info.image
时,您只是在修改这个python对象,而不是查询集。在循环结束时,由于查询集结果由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))
应在不修改模板的情况下工作:)
更新:
我正在考虑另一种解决方案,可能更优雅,当然也更有效:在类模型中添加overlay()函数:
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
在这里,您不需要在视图中或模板中执行任何特殊操作 第二个答案很好,这是我真正应该做的。谢谢