django - 为什么使用视图中的 values() 方法在 img 标签中不显示缩略图?
问题描述
我有一个有 10 个字段的模型。但是在模板中我只想返回四个字段('slug', 'code', 'area', 'thumbnail') 。为此,我在 View 中使用了 Values()。但是缩略图没有显示在模板的img标签中,并且照片的src是空的。视图.py:
def home(request):
allVilla = Villa.objects.filter(status='p').values('slug', 'code', 'area', 'thumbnail')[:8]
context = {
'allvilla': allVilla,
'allproduct': allproduct,
}
return render(request, "wooden/home.html", context)
home.html(模板):
<div id="slider_villa_home" class="owl-carousel owl-theme box_slider_villa dir_left">
{% for v in allvilla %}
<div class="item position-relative box_item wow flipInY">
<div class="position-absolute bg"></div>
<img class="img_item" src="{{ v.thumbnail.url }}" alt="{{ v.code }}">
<p class="position-absolute p_item">
<b>{{ v.code }}</b>
<br>
<b>{{ v.area }}</b>
</p>
<a class="position-absolute link_item" href="{% url 'wooden:singlevilla' v.slug %}">
</a>
</div>
{% endfor %}
</div>
请帮忙
解决方案
如果你使用.values(…)
[Django-doc],那么 Django 将返回一个字典集合。因此,这意味着模型的逻辑层(及其字段)不再起作用,因此v.thumbnail.url
没有意义,因为v.thumbnail
它是一个简单的字符串,因此不再FieldFile
具有.url
属性。
您最好加载模型对象,并使用这些对象,所以:
def home(request):
# no .values() ↓
allVilla = Villa.objects.filter(status='p')[:8]
context = {
'allvilla': allVilla,
'allproduct': allproduct,
}
return render(request, "wooden/home.html", context)
如果您想最小化带宽以仅返回列的一个子集,您可以使用.only(…)
[Django-doc]:
def home(request):
allVilla = Villa.objects.filter(
status='p' # using only ↓
).only('pk', 'slug', 'code', 'area', 'thumbnail')[:8]
context = {
'allvilla': allVilla,
'allproduct': allproduct,
}
return render(request, "wooden/home.html", context)
推荐阅读
- postgresql - 在 PostgreSQL 9.6 中自动真空/真空不释放死行
- vue.js - 如何使用 vee-validation 本地化 vuejs 中的错误消息
- android - 如何以编程方式更改开关颜色?
- c# - 有没有办法在启动期间动态确定 Azure webjob 中触发的队列的数量和名称?
- sql-server - 我想加入两个表并将两行显示为一行
- javascript - 检查文本框jquery中是否存在文本
- cross-validation - 使用交叉验证进行模型调整
- c# - 当它是不同的字符串值 C#(Unity) 时,yIndex 不会递增
- python - 如何创建 bot Telegram 以发送命令 RaspberryPi
- javascript - 敲除订阅执行多次