Django - 类中属性的上下文字典

Jua*_*ano 2 python django dictionary django-queryset

我想在我的Django应用程序中显示一个特定类的属性列表.例如,显示博客文章的所有标题:

Models.py

class BlogPost(models.Model):
    title = models.CharField(max_length=128)
    message = models.CharField(max_length=30)

    def __unicode__(self):
            return self.title
Run Code Online (Sandbox Code Playgroud)

然后在我的上下文字典中我收到错误:

类型对象'BlogPost'没有属性'title'

Views.py

def index(request):
    context = RequestContext(request)
    blog_list = BlogPost.title # I understand here is the issue. 
    context_dict = {'blog': blog_list}
    return render_to_response('rango/blog.html', context_dict, context)
Run Code Online (Sandbox Code Playgroud)

sty*_*ane 5

title是您的模型中的实例属性,这就是为什么您收到此错误消息,据说获取所有title值的列表,您可以使用该.values()方法

blog_list = [post['title'] for post in BlogPost.objects.values('title')]
Run Code Online (Sandbox Code Playgroud)