You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. In attStudName view:

    • You're trying to use mark directly, but students is a queryset (a collection of objects), not a single student's mark. You need to calculate the percentage for each student individually.
    • The variable ttlmark isn't properly assigned per student, so it won't work as intended in your template.
  2. In file_load_view view:

    • After annotating mark=Sum('attendance'), you're trying to access 'attendance' in values_list—but the aggregated field you created is named mark, which will cause an error.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:03:07