对随机图像进行分级会导致 tag.rand_img 上的标题、url(等)属性消失,这意味着我只能显示对象名称。
视图.py:
def locations_gallery(request):
queryset = Photo.objects.all()
tags = Tag.objects.usage_for_queryset(queryset, counts=True)
tags.sort(key=operator.attrgetter('count'), reverse=True)
for tag in tags:
image_tag = Tag.objects.get(name=tag)
tag.rand_img = TaggedItem.objects.get_union_by_model(Photo, image_tag).order_by('?')[:1]
ctxt['tags'] = tags
return render_to_response('locations_gallery.html', ctxt, RequestContext(request))
模板(简化):
{% for tag in tags %}
{{ tag.name }}
<img src="{{ tag.rand_img.url }}">
{% endfor %}