【问题标题】:The function object has no attribute 'entry_set'函数对象没有属性“entry_set”
【发布时间】:2017-02-18 13:36:50
【问题描述】:

关于 Django 正如照片所示 我不知道为什么会有一个AttributeError

from django.shortcuts import render
from .models import Topic
def topic(request, topic_id):
   topics = Topic.objects.get(id=topic_id)
   entries = topic.entry_set.order_by('-date_added')
   context = {'topic': topic, 'entries': entries}
return render(request, 'learning_logs/topic.html', context)

【问题讨论】:

  • 请直接在此处提供示例代码和错误输出,无需外部图片来源。您的问题标题也不是描述性的。它应该能说明问题。
  • 我已经添加了代码。

标签: django


【解决方案1】:

问题可能出在您的主题功能中。您将一个主题分配给topics 变量,然后尝试从名为topic 而不是topics 的变量中获取entry_set。由于您只获得一个主题,因此将topics 变量更改为单数topic 会更有意义:

def topic(request, topic_id):
   topic = Topic.objects.get(id=topic_id)
   entries = topic.entry_set.order_by('-date_added')
   context = {'topic': topic, 'entries': entries}
   return render(request, 'learning_logs/topic.html', context)

【讨论】:

    【解决方案2】:

    您有模型主题和条目,主题通过外键与条目相关。

    然后您可以使用“topic.entry_set.order_by('-date_added')”获取条目

    仅供参考:entry_set is XXX_set.all() XXX 表示入门模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 1970-01-01
      • 2020-04-01
      • 2022-01-14
      • 2016-11-12
      • 2019-05-10
      • 2021-07-21
      相关资源
      最近更新 更多