循环遍历 Django 模板中的对象列表
Posted
技术标签:
【中文标题】循环遍历 Django 模板中的对象列表【英文标题】:Looping over a list of objects within a Django template 【发布时间】:2011-11-10 18:59:03 【问题描述】:似乎看不出我在哪里出错了。原谅我,因为我是新手。我正在尝试在模型中显示 10 个最新的对象。
这是我用来将所有这些对象放在一个列表中的循环:
# put the top 10 newest Recipe objects in a list
entries_list = []
all_recipes = Recipes.objects.annotate(Count('id'))
newest_recipe_index = len(all_recipes)
index = 0
while index < 10:
try:
x = Recipes.objects.get(id=newest_recipe_index)
entries_list.append(x)
newest_recipe_index = newest_recipe_index - 1
index = index + 1
except:
index = index + 1
pass
然后我将它渲染到页面,如下所示:
c = RequestContext(request, 'form' : form, 'entries_list' : entries_list)
return render_to_response("main.html", c)
这是我的html:
% for entries in entries_list %
<i><b>Name:</i></b> entries_list.name <br>
<img src="/images entries_list.picture " ></img><br>
<i><b>Ingredients:</i></b> entries_list.ingredients <br>
<p><i> entries_list.description </i></p>
<i><b>Created by:</i></b> entries_list.user <br><br>
% endfor %
这里是models.py:
class Recipes(models.Model):
name = models.CharField(max_length=50)
ingredients = models.CharField(max_length=300)
picture = models.ImageField(upload_to = 'recipes/%Y/%m/%d')
user = models.CharField(max_length=30)
date = models.DateTimeField(auto_now=True)
description = models.TextField()
comments = models.ManyToManyField(Comments)
似乎循环正在工作。正确数量的条目在那里。只是模板标签不起作用。他们只是空白。因此,将对象放入列表中似乎工作得很好,它只是不会检索我的各个字段。
【问题讨论】:
第一个问题很好。你已经清楚地给了它一个机会并发布了你的代码的重要sn-ps。 【参考方案1】:所以你做了什么: 如果你了解 C 语言的基础.. 你的问题是打印数组的元素,所以你会像..
array = [1,2,3,4,5,6,7]
int i=0;
for(i=0;i<8;i++)
print i; // print array; is wrong
与上述情况类似,您正在迭代 entries_list
并将每个元素分配给变量 entries
。现在你将使用entries
。
% for entries in entries_list %
<i><b>Name:</i></b> entries.name <br>
<img src="/images entries.picture " ></img><br>
<i><b>Ingredients:</i></b> entries.ingredients <br>
<p><i> entries.description </i></p>
% endfor %
当然,@CarL
为您提供了一个更好的解决方案,以获取最新的 10 种配方,以防您的模型。
【讨论】:
【参考方案2】:有几件事。有一种方法可以让您对查询进行排序并获取前十个条目。它会比你拥有的循环更有效。
您的模板不起作用的原因是您指的是列表而不是单个条目。应该是:
% for entry in entries_list %
<i><b>Name:</i></b> entry.name <br>
<img src="/images entry.picture " ></img><br>
<i><b>Ingredients:</i></b> entry.ingredients <br>
<p><i> entry.description </i></p>
<i><b>Created by:</i></b> entry.user <br><br>
% endfor %
一旦你的模板正常工作,试试这个来获取你的条目列表:
entries_list = Recipes.objects.order_by('-id')[0:10]
这是关于排序和切片查询的文档:https://docs.djangoproject.com/en/dev/topics/db/queries
【讨论】:
啊当然!我想我假设因为我将它呈现为“entries_list”:entry_list,所以它会一直在寻找一个模板标记,它说entries_list。但这完全有道理。 我很确定我做了同样的事情——至少一次。以上是关于循环遍历 Django 模板中的对象列表的主要内容,如果未能解决你的问题,请参考以下文章
使用地板循环 jinja django python 遍历列表