[英]Queryset object has no attribute 'Name'
我正在研究我的第一個django項目,我遇到的問題是將我的數據庫中的“類別”顯示在一個網頁列表中。 我收到錯誤“對象沒有屬性'名稱'。到目前為止我的代碼是:
模型:
class Category(models.model):
name = models.Charfield(max_length=128)
def __unicode__(self):
return self.Name + ": " +str(self.id)
瀏覽次數:
from django.shortcuts import render_to_response, redirect
from forms.models import Form, Group, Flow, Gate, Field, Event, Category
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
def homepage (request):
CatName = Category.objects.order_by('id')
output = {
'category_name': CatName.Name,
}
return render_to_response('forms/formsummary.html', output)
HTML:
<div>{{ category_name }}</div>
任何人都能指出我正確的方向嗎?
在Django中,當您使用ORM查詢對象時,有兩種可能性(不包括每種情況都不返回):
在這種情況下,您的查詢返回了一個Category對象的集合,您可以對此做一些事情,您可以使用列表推導生成僅包含名稱的列表:
cnames = [c.name for c in Category.objects.all()]
或者您可以使用for循環迭代列表,並執行您需要對每個對象執行的任何操作。
Django已經通過id字段對您的數據進行了排序,因此,我想在這種情況下無需指定排序。
稍后,當您的視圖返回時,您可以將列表傳遞到模板並迭代它以提取您需要的內容,例如。
在你看來:
def get_categories(request):
categories = Category.objects.all()
context = {'categories': categories}
return render_to_response('template.html', RequestContext(request, context))
然后,在您的模板中:
{% for c in categories %}
<p>{{c.name}}</p>
{% endfor %}
這是一些有用的文檔
希望這可以幫助。
看起來像是區分大小寫的
def__unicode__(self):
return self.Name + ": " +str(self.id)
^
name
CatName
是Category
實例的集合。 CatName
對象沒有name
屬性,因為它不是Category
對象。 它包含Category
對象。
您可以遍歷您的集合並顯示每個類別名稱:
for category in CatName:
print category.name
即使您還沒有完全掌握它,至少可以閱讀QuerySet文檔。
如果您只想要最近的類別,您可以執行以下操作:
def homepage (request):
most_recent_category = Category.objects.order_by('-id')[0]
output = {
'category_name': most_recent_category.name
}
return render_to_response('forms/formsummary.html', output)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.