Как можно разбить на категории набор запросов django в разных диапазонах на основе данных столбцов

enter image description here

я хочу написать django запрос, который может подсчитать оценки студентов в диапазоне [1,30][30,60][60,90][90,100]

на основе предмета в другом курсе

результат что-то вроде enter image description here

Хотя в вашем вопросе нет ни фрагментов кода, ни четкого разъяснения. Но на основе своих предположений я подготовил решение для вашего понимания. Это абстрактная реализация. Но вы получите представление.

В models.py: rom django.db import models

COURSE = [
    ('btech','Btech'),
    ('mtech', 'Mtech'),
    
    #.....and many more
]

SUBJECT = [
     ('math','Math'),
    ('os', 'OS'),
        ('science', 'Science'),

    #.....and many more
]

MARKS_RANGE = [
     ('0-30','0-30'),
    ('31-60', '31-60'),
    #.....and many more
]
class StudentMarks(models.Model):
    student_id = models.IntegerField()
    course = models.CharField(max_length=25, choices=COURSE)
    subject = models.CharField(max_length=25, choices=SUBJECT)
    marks_range = models.CharField(max_length=25, choices=MARKS_RANGE, null=True, blank=True)
    marks = models.DecimalField(max_digits=5,decimal_places=2,)

    def save(self, *args, **kwargs):
        if self.marks>0 and self.marks<31:
            self.marks_range ="0-30"
        elif self.marks>30 and self.marks<61:
            self.marks_range ="31-60"

            ''' any many more'''
        super().save(*args, **kwargs)

    def __str__(self) -> str:
        return self.course + " " + self.subject + " "+self.marks_range

в admin.py:

from django.contrib import admin

from trial.models import StudentMarks

admin.site.register(StudentMarks)

в views.py:

from django.shortcuts import render
from django.db.models import Count
from .models import StudentMarks



def course_wise_result_view(request):
    queryset=StudentMarks.objects.values('subject','course',
    'marks_range').order_by().annotate(marks_range_count=
    Count('marks_range')  )
    
    context = {}
    subjects = set()
    courses = set()
    for qs in queryset:
        subjects.add(qs['subject'])
        courses.add(qs['course'])
    
    for course in courses:
        context[course]=queryset.filter(course=course).values(
            'subject', 'marks_range','marks_range_count',)

        

    return render(request, 'trial.html',
    {'qs':queryset,'subjects':subjects,'courses':courses, 
    'context_btech':context['btech'], 'context_mtech':context['mtech']})

Наконец, в шаблоне:

<html>
<table class="table table-striped">
  
   <h1>BTech</h2>
    <tr>
    <th>Subject</th> <th>Mark Range</th>  <th>Total</th>
    </tr>
{% for i in context_btech %}
   <tr>

   {% ifchanged i.subject %}<th>{{i.subject}}</th>
   {%else%}
   <th></th>
   {% endifchanged %} 
    <td>{{i.marks_range}}</td>
   <td>{{i.marks_range_count}}</td></tr> 
{% endfor %}


</table>
<br>
<hr>
<table class="table table-striped">
  
    <h1>MTech</h2>
     <tr>
     <th>Subject</th> <th>Mark Range</th>  <th>Total</th>
     </tr>
 {% for i in context_mtech %}
    <tr>
 
    {% ifchanged i.subject %}<th>{{i.subject}}</th>
    {%else%}
    <th></th>
    {% endifchanged %} 
     <td>{{i.marks_range}}</td>
    <td>{{i.marks_range_count}}</td></tr> 
 {% endfor %}
 
 
 </table>
 
 
 </html>

</html>

Run the snippet to view the template:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">

<html>
    


<table class="table table-striped">
  
   <h1>BTech</h2>
    <tr>
    <th>Subject</th> <th>Mark Range</th>  <th>Total</th>
    </tr>

   <tr>

   <th>math</th>
    
    <td>0-30</td>
   <td>3</td></tr> 

   <tr>

   
   <th></th>
    
    <td>31-60</td>
   <td>2</td></tr> 

   <tr>

   <th>os</th>
    
    <td>31-60</td>
   <td>1</td></tr> 



</table>
<br>
<hr>
<table class="table table-striped">
  
    <h1>MTech</h2>
     <tr>
     <th>Subject</th> <th>Mark Range</th>  <th>Total</th>
     </tr>
 
    <tr>
 
    <th>math</th>
     
     <td>0-30</td>
    <td>1</td></tr> 
 
    <tr>
 
    <th>os</th>
     
     <td>0-30</td>
    <td>1</td></tr> 
 
    <tr>
 
    
    <th></th>
     
     <td>31-60</td>
    <td>1</td></tr> 
 
    <tr>
 
    <th>science</th>
     
     <td>31-60</td>
    <td>1</td></tr> 
 
 
 
 </table>
 
 
 </html>

</html>

Надеюсь, у вас появится идея.

Вернуться на верх