Django将查询对象分配到数组中

时间:2011-05-15 13:36:08

标签: django django-templates

如何将查询对象分配到数组中?如何将测试分配到test_list?这样我就可以将它分配给模板使用了。 模板可以迭代列表吗?

test_list = []

tests = Test.objects.all()

for test in tests:
   test_list.append(test)

return render_to_response('index.html', 
                         {'tests':test_list},)

模板:

{% for test in tests %}
    {{ test.name|safe }}
{% endfor %}

我收到此错误:

Caught TypeError while rendering: 'Test' object is not iterable

2 个答案:

答案 0 :(得分:1)

问题是为什么要将Test.objects.all的结果放在“数组”中? (在python中称为list

在你的代码中,tests是一个queryset对象,它已经支持大多数“数组”操作,包括切片等等。编辑:这也意味着你可以在模板中访问和迭代它们。 (django模板可以迭代任何“可迭代的”python对象。

其次,你可能应该让数据库进行查询,因为它会更有效地使用django queryset filter

test = Test.objects.all(quantity__gt = 0)

如果你仍然想要一个列表,那么创建一个列表的好方法是使用list comprehension

test_list = [test.objects.all()中的test测试,如果test.quantity> 0]

答案 1 :(得分:0)

比Django更多的是Python问题,但是使用append()函数。

#don't use this one for your use case!
for test in tests:
  if test.quantity > 0:
     test_list.append(test)

此外,在数据库中进行过滤更为合适

# get all items the quantity of which is greater than 0
tests = Test.objects.filter(quantity__gt=0)

您当前的代码不正确,因为:

tests = Test.objects.all()
for test in tests:
  # this statement is meaningless, it is always executed, you can just omit
  # this
  if True:
     #you are overwriting/-defining test_list variable
     #should be test_list.append(test)

     test_list = test