TypeError в ManyRelatedManager

Пожалуйста, помогите мне с этим кодом. Код показывает, что объект 'ManyRelatedManager' не является итерируемым введите описание изображения здесь

def index(request):
    parms = {
        'posts': Post.objects.filter(publish = True),
    }
    return render(request, 'index.html',parms)

Код индекса:

{% extends 'base.html' %}
{% block body %}
{% load static %}
    <div class="site-section py-0">
      <div class="owl-carousel hero-slide owl-style">
        {% for post in posts|slice:":5" %}
        <div class="site-section">
          <div class="container">
            <div class="half-post-entry d-block d-lg-flex bg-light">
              <div class="img-bg" style="background-image: url({{post.thumbnail.url}})"></div>
              <div class="contents">
                <span class="caption">{{post.author.user.username}}</span>
                <h2><a href="blog-single.html">{{post.title}}</a></h2>
                <p class="mb-3">{{post.overview}}</p>
            


                <div class="post-meta">
                  <span class="d-block">

                    {% for cate in post.categories %}
                      <a href="#">{{cate.title}}</a>
                    {% endfor %}

                  </span>
                  <span class="date-read">{{post.time_upload}}<span class="mx-1">&bullet;</span>{{post.read}} reads<span class="icon-star2"></span></span>
                </div>

              </div>
            </div>
          </div>
        </div>
        {% endfor %}

кодview.py:

from django.shortcuts import render
from .models import Post

def index(request):
    parms = {
        'posts': Post.objects.filter(publish = True),
    }
    return render(request, 'index.html',parms)

def about(request):
    parms = {
        'title': 'About | Blogie'
    }
    return render(request, 'about.html',parms)

def categories(request):
    return render(request, 'categories.html')

def post(request):
    return render(request, 'blog-single.html')

def contact(request):
    return render(request, 'contact.html')

post.categories является менеджером, а не QuerySet, вы должны использовать .all для доступа к QuerySet:

{% for cate in post.categories.all %}
    <a href="#">{{cate.title}}</a>
{% endfor %}

Вы можете повысить эффективность с помощью .prefetch_related(…) [Django-doc] в представлении:

def index(request):
    parms = {
        'posts': Post.objects.filter(publish=True).prefetch_related('categories')
    }
    return render(request, 'index.html',parms)
Вернуться на верх