is there any length function for the Django Model Objects?

Viewed 206

I've hard coded this 3 in my loop range because I was unable to get the actual length. I tried listing the available features but didn't found any print(dir(Todo_Item.objects)). Maybe is there any other better way to iterate over the object and stop when it ends? This is my code with hard coded 3 in loop range.

def home_view(request):
display_list = []
for i in range(3):
    display_list.append(Todo_Item.objects.get(id=i+1).task)
.......some code below as well.......

My Todo app runs fine without any error but the only problem is this non-dynamic loop. enter image description here

2 Answers

I am a little rusty with Django, but I think what you want is to fetch all of the Todo_Items in one go and iterate over them. For that, you would want to use the all() method to fetch an entire QuerySet. With that, you can iterate over each item it returns using len:

def home_view(request):
    display_list = []
    todo_items = Todo_Item.objects.all()
    for item in len(todo_items):
        display_list.append(item.task)
    .......some code below as well.......

Again, I am pretty out of practice using Django, but I think there is also a way to fetch the task value for each item you select all in one go, but I cannot remember exactly how. Django has a powerful query syntax, so check out these pages to learn more:

https://docs.djangoproject.com/en/3.1/topics/db/queries/ https://docs.djangoproject.com/en/3.1/ref/models/querysets/

If you don't need anything filtration, you can do that:

todo_items = Todo_Item.objects.all()
for item in todo_items:
    print(item.task)

also you can iterate over it into your template:

{% for item in todo_items %}
        <li>{{ item.task }}</li>
{% endfor %}

Preliminary add todo_items into render context.

Related