kitchen800
kitchen800

Reputation: 227

how to count up and show database table entries Django

I am using chartsjs to generate charts. i have set my chart labels to:

Index.py

 labels: [

  {% for number in the_numbers_from_Floating %}
      "week " + {{ number.pk }},
   {% endfor %}

],

Views.py

def index(request):
the_numbers_from_Floating = Floating.objects.all()

return render(request, "index.html", {
    'the_numbers_from_Floating': the_numbers_from_Floating,
                                      })

my problem is that i am setting my label to the pk of my database table. If entries are deleted and new entries are added then the pk value rises. hence throwing off my labels seen below in the pictures. to fix this i should set it so that i am iterating up to the count() of my table. but how can i do that?

enter image description here enter image description here

Upvotes: 0

Views: 79

Answers (1)

Igor Moraru
Igor Moraru

Reputation: 7739

You could define label indexes using range:

def index(request):

    the_numbers_from_Floating = Floating.objects.all()

    return render(request, "index.html", {
        'the_numbers_from_Floating': the_numbers_from_Floating,
        'label_indexes': range(1, the_numbers_from_Floating.count()+1)
        })

Then in template:

 labels: [

  {% for index in label_indexes %}
      "week " + {{ index }},
   {% endfor %}

],

Upvotes: 1

Related Questions