__в фильтре, возвращающем только одно значение, покажите запрос через промежуточную таблицу

Новичок в кодировании и нужна помощь. Я пытаюсь вывести представление article путем фильтрации через модель Spots. У меня есть промежуточная таблица ArticleSpots, чтобы связать 2 таблицы Spots и Articles. В представлениях article я хочу показывать только те места, которые связаны с конкретной статьей. Моя проблема в том, что Spots.objects.filter(id__in=articleSpots) показывает только первое значение, а не все места, на которые есть ссылки. Что я делаю не так?

views.py

def article(request, slug):
    articles = get_object_or_404(Articles, slug=slug)
    article_id = articles.id
    articleSpots = ArticleSpots.objects.filter(article__id=article_id)    
    spots = Spots.objects.filter(id__in=articleSpots)
    
    context = {"spots": spots, "articles": articles}
    template_name = "articletemplate.html"
    return render(request, template_name, context)

models.py

class ArticleSpots(models.Model):
    article = models.ForeignKey('Articles', models.DO_NOTHING)
    spot = models.ForeignKey('Spots', models.DO_NOTHING)

    class Meta:
        managed = True
        db_table = 'article_spots'
        verbose_name_plural = 'ArticleSpots'
        
    def __str__(self):
        return str(self.article) + ": " + str(self.spot)

class Articles(models.Model):
    title = models.CharField(max_length=155)
    metatitle = models.CharField(max_length=155)
    slug = models.SlugField(unique=True, max_length=155)
    summary = models.TextField(blank=True, null=True)
    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')

    class Meta:
        managed = True
        db_table = 'articles'
        verbose_name_plural = 'Articles'
        
    def __str__(self):
        return str(self.id) + ": " + str(self.title)

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)

html

<!-- START MAIN -->
    <main class="page"></main>
    <p>
      {{ spots.title }} <br />
      {{ spots.content1 }} <br />
      {{ articles.title }}
    </p>
    {% for spots in spots %} {{ spots.title}} {% endfor %}
<!-- END MAIN -->

В настоящее время вы получаете Spots, которые имеют тот же первичный ключ, что и объект ArticleSpots, но это не имеет особого смысла: возможно, что это так, но даже если это произойдет, возвращенный Spots сам по себе не связан с соответствующим ArticleSpots с данной статьей.

Вы можете получить соответствующие Spots с помощью:

def article(request, slug):
    article = get_object_or_404(Articles, slug=slug)
    spots = Spots.objects.filter(articlespots__article=article)
    context = {'spots': spots, 'article': article}
    return render(request, 'articletemplate.html', context)

Я бы настоятельно советовал назвать Article объект article, поскольку он является единичным Article, а не коллекцией Article. С другой стороны, spots - это коллекция пятен.

Выводить {{ spots.content1 }} и {{ spots.title }} не имеет смысла, так как spots является коллекцией Spots, которая может содержать ноль, один или более элементов.

Таким образом, шаблон должен выглядеть следующим образом:

<p>
    {{ article.title }}
</p>
{% for spot in spots %} {{ spot.title}} {% endfor %}

Примечание: обычно модели Django дается сингулярное имя, поэтому Articles вместо Article.

Вернуться на верх