[英]Can't add extra information to model in view
我正在尝试向视图中的对象添加一些额外的信息:
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对象,而不是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))
应该可以正常工作,而无需修改模板:)
更新:我正在考虑其他解决方案,也许更优雅并且肯定更有效:向您的Model类添加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
在这里,您不需要在视图或模板中做任何特别的事情!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.