从标记库中选择随机项目
对随机图像进行分级会导致 tag.rand_img 上的标题、url(等)属性消失,这意味着我无法显示除对象名称之外的任何内容。
view.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 %}
Gradding a random image causes the title, url (etc) attributes on the tag.rand_img to vanish, meaning I can't display anything more than the object name.
view.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))
Template (simplified):
{% for tag in tags %}
{{ tag.name }}
<img src="{{ tag.rand_img.url }}">
{% endfor %}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此行:
返回查询集,而不是模型实例。查询集没有您的自定义方法,它们仅存在于该查询集中的实例上。
将
[:1]
替换为[0]
以获取实际的模型实例(如果没有,您需要捕获IndexError
t 匹配的项目)。This line:
is returning a Queryset, not a model instance. The queryset doesn't have your custom methods, they exist only on the instance within that queryset.
Replace the
[:1]
with[0]
to get the actual model instance (you'll need to catchIndexError
in case there isn't a matching item).我首先获取标签:
然后迭代它们并将图像添加为额外字段。然后您可以执行模板中概述的操作。
I'd first get the tags:
and then iterate through them and add the image as an extra field. Then you could do something like you've outlined in your template.
您可以添加类似的属性,Python 会允许这样做,但您将不再处理
QuerySet
。试试这个:
然后在你看来
You can add attributes like that, Python will allow it but then you are no longer working on a
QuerySet
.Try this:
Then in your view