0

Im new to django and Im helping in creating a website, now what they've requested is to show a specific number and Im trying to use a for loop it goes something like this:

    class Students(models.Model):
...
section = (('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'))
BlockNumber = models.CharField(max_length=10, choices=section)

now what I want to do is to count each section choice in the Students model class. I've tried using the code below to count each choice:

def yearCount(request):
    year = Students.objects.all(Count('year'))
    blocks = Students.onjects.all(Count('section'))
    context = {'year': year,'blocks': blocks}
    return render(request, './chairperson/students/student_bsit1.html', context)

Any help would be appreciated, thank you.

  • `count each section choice in the Students model class` can you elaborate this...?? and what is the sample result which you are expecting...?? – Shivendra Pratap Kushwaha Jun 10 '21 at 08:59
  • Are you trying to get a count of the number of students which have 1 as their section, 2 as their section and so on? If so have a look here: https://stackoverflow.com/questions/30752268/how-to-filter-objects-for-count-annotation-in-django – Dean Elliott Jun 10 '21 at 09:12
  • `blocks = Students.onjects.all(Count('section'))` has a rogue `n` in `objects` – obrunt Jun 23 '23 at 15:10

1 Answers1

1

If you are trying to count on the number of students with particular sectors from your choices:

from django.db.models import Q, Count
student_counts = Students.objects.annotate(
    section1_count=Count('BlockNumber', filter=Q(BlockNumber='1')),
    section2_count=Count('BlockNumber', filter=Q(BlockNumber='2')),
    # section3_count... etc
)

You mentioned your new to Django so see here's a couple notes/tips on code styling, your model names should be plural. Students should be Student and your fields should be block_number instead of BlockNumber. Functions should be year_count instead of yearCount. Here is a good article to improve your code readability and maintainability. It would be good to get a linter up and running on your editor to help with this earlier in the project so you can get used to the Python style guides.

Dean Elliott
  • 1,245
  • 1
  • 8
  • 12