简体   繁体   中英

Django query show length in a template?

I am trying output the length of my query in a template . What is the right method to do that?

I have tried len() ,. count() , count() but nothing worked .

here is my views.py :

@login_required
def view_contacts(request):
    print("Current User")
    current_user = request.user.get_username()
    user = User.objects.filter(username=current_user).first()

    output = UserContacts.objects.filter(current_user_id=user.id).first()

    my_dict = {'output':output,'number': output.count}

    return render(request,'basic_app/view_contacts.html',my_dict)

and this is my view.contacts.html :

{%extends 'basic_app/base.html' %}
{% block body_block %}

<div class = "jumbotron">   

        <p> you have {{ number }} of contacts in your address book</p>
        <p> {{ output }} </p>

</div>


{% endblock %}

Any help would be greatly appreciated

Error:

UserContacts object has no attribute count

Here in your query the first() method will return the single object which is at first so you can't count.

Remove the first() and call the count() method like this.

output = UserContacts.objects.filter(current_user_id=user.id)
count = output.count()

you should replace

output = UserContacts.objects.filter(current_user_id=user.id).first() 

to output = UserContacts.objects.filter(current_user_id=user.id).all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM