python - Object_list 在模板中未显示正确的数据

标签 python django python-3.x web django-2.1

我在 Django 模板中遇到了一个奇怪的问题。它是一个显示文章列表的模板,我为每个人显示了一个我称之为关键概念的关键字列表。

奇怪的是,它显示的不是关键概念列表,而是使用该关键概念的文章列表。

下面是我的项目的E/R图以及模型和模板: enter image description here

模型.py

class KeyConceptModel(models.Model):
    concept_text = models.CharField(max_length=50)

    def __str__(self):
        return self.concept_text

    def get_absolute_url(self):
        return reverse("keyconceptManuscriptusView", kwargs={"pk": self.pk})

    class Meta: 
        verbose_name = "Concetto chiave"
        verbose_name_plural = "Concetti chiave"  

class PostModel(models.Model):
    post_title = models.CharField(max_length=70)
    post_short_description = models.TextField(max_length=200)
    post_contents = models.TextField()
    post_publishing_date = models.DateTimeField(auto_now=False, auto_now_add=True)
    post_author = models.ForeignKey(AuthorModel, on_delete=models.CASCADE)
    post_keyconcept = models.ManyToManyField(KeyConceptModel)
    slug = models.SlugField(verbose_name="Slug", unique="True")
    post_highlighted = models.BooleanField(default=False)

    def __str__(self):
        return self.post_title

    def get_absolute_url(self):
        return reverse("singlepostManuscriptusView", kwargs={"slug": self.slug})

    class Meta: 
        verbose_name = "Articolo"
        verbose_name_plural = "Articoli" 

View .py

class ListPostGDV(ListView):
    model = PostModel
    template_name = "manuscriptus_home.html"

模板

{% for posts in object_list %}
  <div id="news" class="container">
    <div class="row">
      <img class="img-fluid" src="{% static 'manuscriptus/img/demo_img.png' %}" alt="Header image">
    </div>
    <div class="row">
      <div class="col-3">
        <div class="row">
          <small class="text-muted">Pubblicato il <strong>{{ posts.post_publishing_date|date }}</strong></small>
        </div>
        <div class="row">
          {% for keyword in object_list.all %}
              <p>{{ keyword }}</p>
          {% endfor %}
        </div>
      </div>
      <div class="col-9">
        <div class="row">
          <p class="h3"><a href="{{ posts.get_absolute_url }}">{{ posts.post_title }}</a></p>
        </div>
        <div class="row">
          <p class="h5">{{ posts.post_short_description|safe|linebreaks }}</p>
        </div>
      </div>
    </div>
  </div>
{% empty %}
  <div id="news" class="container">
    <h1>Go to the admin panel and create your first post!</h1>
  </div>
{% endfor %}

NB: I've used the generic detail views

最佳答案

在模板中写入:

<!-- this will iterate again over the <i>same</i> list -->
{% for keyword in <b>object_list.all</b> %}
    <p>{{ keyword }}</p>
{% endfor %}

但是这里的object_list是您的文章的QuerySet。您调用 .all() 的事实仅意味着 for 循环将再次迭代所有 PostModel s(.all() 用于明确表明您不进行过滤)。

如果您想迭代 post_keyconcept,则需要调用 posts.post_keyconcept.all:

{% for keyword in <b>posts.post_keyconcept.all</b> %}
    <p>{{ keyword }}</p>
{% endfor %}

由于您要渲染所有 postskey_concepts,因此最好在 ListView 中使用 .prefetch_lated(..) 使得在恒定数量的查询中获取关键字,因此:

class ListPostGDV(ListView):
    model = PostModel
    queryset = PostModel.objects<b>.prefetch_related('post_keyconcept')</b>

    # ...

Note: normally the names of models are singular and without the Model suffix, so Post instead of PostModel, and KeyConcept instead of KeyConceptModel.

 

Note: since you iterate over object_list (in the outer loop) the item is a single post, so I advice to name it post, instead of posts, since this otherwise only introduces confusion.

 

Note: you prefix all attributes with post_ which is a bit redundant. It also prevents making use of duck typing when for example two models have a name attribute, and you want the function to be able to process both. Therefore I advise to remove the post_ prefix of the attributes.

关于python - Object_list 在模板中未显示正确的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52242818/

相关文章:

python - xlabel、ylabel 不工作。 'str' 对象不可调用

django - 浏览器缓存我的页面的非常奇怪的问题,即使被指示不要

python - Django 模板扩展

python - Django 1.10 RequestContext 处理器不工作

python-3.x - 类型错误 : 'Tensor' object is not callable | Keras-Bert

python - PyQt 用字典发出信号

python - 如何在 while 循环中使用用户输入修改矩阵,并在用户输入字符串时中断?

python - 是否有等同于 PyVirtualDisplay 的 Windows

python - 查找二维数组中具有某些非零元素的列的索引

python - 在 python 中导入模块时会发生什么