python - 尝试使用外键从不同类中按字段进行选择,出现错误

标签 python html django view

我正在创建一个 reddit 克隆作为个人项目来掌握 django,到目前为止我已经有两个类:

from django.db import models
from django.contrib.auth.models import User

class Board(models.Model):
    name = models.CharField(max_length =100, blank = False)
    created_on = models.DateTimeField('Date Created', auto_now_add=True)
    deleted = models.BooleanField(default = False)

    def __unicode__(self):
        return self.name

class Notice(models.Model):
    title = models.CharField(max_length=200) #title as it appears on the notice
    author = models.ForeignKey(User, null=False, blank=False)
    posted_on = models.DateTimeField('Posted On', auto_now_add= True)
    updated_on = models.DateTimeField('Last Updated', auto_now = True)
    board = models.ForeignKey(Board, null=False)
    isText = models.BooleanField(null=False, blank = False)
    content = models.TextField()
    thumps_up = models.PositiveIntegerField()
    thumps_down = models.PositiveIntegerField()
    deleted = models.BooleanField(default=False)

    def __unicode__(self):
        return self.title

在我的网址中我有:

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^(?P<board_name>\w+)/$', views.board_lv)
)

我想要做的是使用“Notice”模型中的“board”外键将网址模式与“Board”模型中的“name”字段进行比较,然后打开一个列出所有通知的页面with 在该板上(类似于 reddit 中的 subreddits)。

我收到一个类型错误“注意对象不可迭代”,这让我认为我只有一个对象而不是列表,但我不应该这样做我?

迭代位于noticeList.html文件的这部分;

{% for n in latest_notices %}
    <li>
    {% if not n.isText %} 
        <h2><a href="{{ n.content }}">{{ n.title }}</a></h2>            
    {% else %}
        <h2>{{ n.title }}</h2>
        <p>{{ n.content }}</p>
    {% endif %}
    </li>
{% endfor %}

View 在哪里:

from django.shortcuts import render, get_object_or_404
from notices.models import Board, Notice

def index(request):
    latest_notices = Notice.objects.order_by('-posted_on')
    context = {'latest_notices': latest_notices}
    return render(request, 'noticeList.html', context)

def board_lv(request, board_name):
    latest_notices = get_object_or_404(Notice, board__name=board_name)
    context = {'latest_notices': latest_notices}
    return render(request, 'noticeList.html', context)

此外,在错误回溯中,board_name 变量值在带引号的字符串之前有一个“u”,例如:

Variable        Value
board_name      u'worldnews'

如果我的网址模式错误或没有充分解释问题,请告诉我,我们将不胜感激。

编辑:完整回溯错误

Traceback:
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/adnan/Documents/django-noticeboard/noticeboard/notices/views.py" in board_lv
  13.   return render(request, 'noticeList.html', context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/shortcuts/__init__.py" in render
  53.     return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/loader.py" in render_to_string
  177.         return t.render(context_instance)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/base.py" in render
  140.             return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/base.py" in _render
  134.         return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/base.py" in render
  830.                 bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/debug.py" in render_node
  74.             return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/defaulttags.py" in render
  284.                 return nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/base.py" in render
  830.                 bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/debug.py" in render_node
  74.             return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.2-py2.7.egg/django/template/defaulttags.py" in render
  147.             values = list(values)

Exception Type: TypeError at /b/worldnews/
Exception Value: 'Notice' object is not iterable

最佳答案

问题在于 get_object_or_404(Notice, board__name=board_name) 返回一个 Notice 模型实例,并且它不可迭代。

一种可能的解决方案是将其添加到列表中并传递到上下文:

def board_lv(request, board_name):
    latest_notices = get_object_or_404(Notice, board__name=board_name)
    context = {'latest_notices': [latest_notices]}
    return render(request, 'noticeList.html', context)

更新下一个错误:然后,如果每个板可能有多个通知,则不要使用get_object_or_404。使用过滤器:

def board_lv(request, board_name):
    latest_notices = Notice.objects.filter(board__name=board_name)
    context = {'latest_notices': latest_notices}
    return render(request, 'noticeList.html', context)

希望有帮助。

关于python - 尝试使用外键从不同类中按字段进行选择,出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18411503/

相关文章:

python - 如何获得Python的等价物[:-1] in django ORM?

python,绘图和c api

python - 新手自学python,我还应该学习什么?

python - 无法在 Django 中加载 .css 和图像文件

html - 如何使 <a> 在边框中可点击?

python - 突然出现导入错误

来自继承自 models.Model 的类的 python 子类

Python OpenCV 无法处理视频

python - 计算pyspark中数据帧所有行之间的余弦相似度

javascript - 平均分隔按钮间距并使其响应