Django assign query object into array
How do I as开发者_运维知识库sign query object into array? How do I assign test into test_list? So that I can assign it to use at template. Can the template iterate the list?
test_list = []
tests = Test.objects.all()
for test in tests:
test_list.append(test)
return render_to_response('index.html',
{'tests':test_list},)
The template:
{% for test in tests %}
{{ test.name|safe }}
{% endfor %}
I get this error:
Caught TypeError while rendering: 'Test' object is not iterable
The question is why would you want to have the results of Test.objects.all in an "array"? (its called a list in python)
In your code, tests is a queryset object, that already supports most of an "array" operations, including slicing, etc.. etc.. Edit: That also means you can access and iterate them in the template. (django templates can iterate any "iterable" python object afaik.
Secondly, you probably should let the database do the querying, as it will do it more efficiently, using django queryset filter
test = Test.objects.all(quantity__gt=0)
If you still want a list, a nice way to create one is using a list comprehension:
test_list = [test for test in Test.objects.all() if test.quantity > 0]
More of a Python question than Django one really, but use the append() function.
#don't use this one for your use case!
for test in tests:
if test.quantity > 0:
test_list.append(test)
Also, it would be more appropriate to do the filtering in the database
# get all items the quantity of which is greater than 0
tests = Test.objects.filter(quantity__gt=0)
your current code is not correct because:
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
精彩评论