django - 用于中间图像表的 Django ORM 给出错误“精确查找的 QuerySet 值必须限制为一个结果”
问题描述
我有多个Images
与Spots
使用中间表相关联ImageSpots
,我正在尝试为每个点渲染每个图像,但不断收到错误“精确查找的 QuerySet 值必须限制为使用切片的一个结果。”。有人可以帮我弄清楚我做错了什么吗?
models.py
class Spots(models.Model):
title = models.CharField(max_length=155)
metatitle = models.CharField(max_length=155)
slug = models.SlugField(unique=True, max_length=155)
author = models.ForeignKey(Authors, models.DO_NOTHING)
field_created = models.DateTimeField(db_column='_created', blank=True, null=True)
field_updated = models.DateTimeField(db_column='_updated', blank=True, null=True)
cover = models.ImageField(upload_to="cover", blank=True, default='logo-00-06.png')
summary = models.TextField(blank=True, null=True)
content1 = models.TextField(blank=True, null=True)
content2 = models.TextField(blank=True, null=True)
class Meta:
managed = True
db_table = 'spots'
verbose_name_plural = 'Spots'
def __str__(self):
return str(self.id) + ": " + str(self.title)
class Images(models.Model):
note = models.CharField(max_length=100, blank=True, null=True)
image = models.ImageField(upload_to="images", blank=True, default='logo-00-06.png')
class Meta:
managed = True
db_table = 'images'
verbose_name_plural = 'Images'
def __str__(self):
return str(self.id) + ": " + str(self.note)
class ImageSpots(models.Model):
images = models.ForeignKey('Images', models.DO_NOTHING)
spots = models.ForeignKey('Spots', models.DO_NOTHING)
class Meta:
managed = True
db_table = 'image_spots'
verbose_name_plural = 'ImageSpots'
def __str__(self):
return str(self.spots) + ": " + str(self.images)
views.py
def article(request, slug):
article = get_object_or_404(Articles, slug=slug)
spots = Spots.objects.filter(articlespots__article=article).distinct()
images = Images.objects.filter(imagespots__spots=spots)
context = {'spots': spots, 'article': article, 'images':images}
return render(request, 'articletemplate.html', context)
html
<main class="page"></main>
<p>{{ article.title }}</p>
{% for spots in spots %} {{ spots.title }}
{% for images in images %}
<img style="width: 200px; height: 200px" src="{{ images.image.url }}" />
{% endfor %} {% endfor %}
解决方案
{% for spots in spots %}
应该{% for spot in spots %}
编辑:
我也发现了这个错误。
images = Images.objects.filter(imagespots__spots=spots)
应该:
images = Images.objects.filter(imagespots__spots__in=spots)
因为ImageSpot
有一个 ForeignKeySpots
是一个对象,你试图通过给它一个列表来过滤它。所以你需要使用__in
.
推荐阅读
- flask - 为什么使用 gunicorn 运行时,线程在 Flask 应用程序中不起作用?
- r - 如何删除 R 中重复/不需要的边界线段?
- html - 如何处理同时具有多个输入和多个文件的请求
- python - 计算时间序列 pandas 数据帧的滚动平均值、最大值、最小值、标准差
- ansible - Ansible delegate_to:在远程主机上运行的 localhost 任务
- reactjs - react-scripts jest 27 版本依赖错误
- keras - LSTM 模型只给出一个标签和二进制精度
- javascript - 是否可以使用 Javascript 触发浏览器的选项卡加载动画(微调器)?
- pine-script - 无法使用样式设置
- javascript - AJAX 帖子收到奇怪的文本响应