Django views.py中能否使用if-else将成绩转换为百分比?
回答
Absolutely, using if-else statements in Django views is not only allowed but also a standard approach to implement custom score-to-percentage conversion logic like you described. Let's walk through fixing your current code and adding your desired logic.
First, let's address issues in your existing code
In
attStudNameview:- You're trying to use
markdirectly, butstudentsis a queryset (a collection of objects), not a single student's mark. You need to calculate the percentage for each student individually. - The variable
ttlmarkisn't properly assigned per student, so it won't work as intended in your template.
- You're trying to use
In
file_load_viewview:- After annotating
mark=Sum('attendance'), you're trying to access'attendance'invalues_list—but the aggregated field you created is namedmark, which will cause an error.
- After annotating
Here's the corrected code with your custom percentage logic
First, let's make a reusable helper function to handle the score-to-percentage conversion (this keeps your code clean and avoids duplication):
def calculate_percentage(mark): # Implement your custom if-else rules here if mark == 200: return 100 elif mark == 100: return 90 # Add more custom conditions as needed else: # Fallback to proportional calculation if no match return round((mark / 200) * 100, 2)
Updated attStudName view (for template display)
def attStudName(request): students_queryset = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance')) # Convert queryset to a list of dicts with percentage added students = [] for student in students_queryset: student_percentage = calculate_percentage(student['mark']) students.append({ 'name': student['studName__VMSAcc'], 'mark': student['mark'], 'percentage': student_percentage }) context = { 'students': students, } return render(request,'show-name.html', context)
Update your template to display the percentage column:
<div id="info" style="padding-left: 130px"> <table class="table table-hover" style="width: 1200px;"> <thead> <tr> <th>Student Name</th> <th>Attendance Mark</th> <th>Percentage</th> </tr> </thead> <tbody> {% for student in students %} <tr> <td>{{ student.name }}</td> <td>{{ student.mark }}</td> <td>{{ student.percentage }}%</td> </tr> {% endfor %} </tbody> </table> <a href="{% url 'export_data' %}">export data</a> </div>
Updated file_load_view view (for CSV export with percentages)
import csv from django.http import HttpResponse def file_load_view(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="report.csv"' writer = csv.writer(response) writer.writerow(['Student Name', 'Attendance Mark', 'Percentage']) students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance')) for student in students: percentage = calculate_percentage(student['mark']) writer.writerow([ student['studName__VMSAcc'], student['mark'], f"{percentage}%" ]) return response
Key Notes
- Using a helper function ensures your conversion logic is consistent across both the template display and CSV export—no duplicated code!
- Test your custom if-else conditions to make sure they cover all possible score values you expect.
- The CSV export now includes the percentage column, matching what's shown in your template.
内容的提问来源于stack exchange,提问作者Puteri
相关产品推荐
相关产品推荐

