0

我有多个ImagesSpots使用中间表相关联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 %}
4

1 回答 1

0

{% 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.

于 2021-10-23T07:40:30.660 回答