Home > Back-end >  How to add counter that increments after an object is created in Django?
How to add counter that increments after an object is created in Django?

Time:06-19

I am making a simple list website that displays a list of movies I want to watch. So, basically, I use a form to add a movie to my list. Nothing fancy, but I want to display a count variable alongside each movie I add to my list from like 1-10 and I want it to increase/decrease based on if I delete/add a new movie. Where would I need to add this? I have separate views for my addition/deletion of movies (objects)

CodePudding user response:

You want to just query the database for how many movies are in the list as that is the equivalent information. Whenever you can derive state you probably should unless there are serious performance repercussions. To get the "counter" then you would basically just need code like:

MovieType.objects.count()

I think although I haven't used Django in years. The point is to count the objects in the database

CodePudding user response:

Stand out part of the question, "I want to display a count variable alongside each movie I add to my list from like 1-10 and I want it to increase/decrease based on if I delete/add a new movie".

What I think you need is to use the forloop counter when iterating over the list of movies you have. For example, in your template:

# i.e.: If your queryset name is movies 
<h3>There are {{ movies.count }} movies on my list.</h3>  # The display of the total amount of movies in the database

# I'm using a table to layout list
<table>
     <thead>
          <th>No.</th>
          <th>Movie Name</th>
          # other columns
     </thead>

     <tbody>
          {% for movie in movies %}
               <tr>
                    # within the loop, there's a counter called 'forloop.counter'. It starts counting from 1 to n number of movies.
                    <td>{{ forloop.counter }}</td>

                    <td>{{ movie.name }}</td>
                    
                    # other movie details
               </tr>
          {% endfor %}
     </tbody>
</table>

So let's say we have 3 movies on our list, what would happen is that the list/table would look like:

# There are 3 movies on my list.

# No.      Name                           Other details 
# 1        Jack Sparrow Team              Details 
# 2        Game Night                     Details    
# 3        The Great Stackoverflow Show   Details

I hope that's what you meant.

  • Related