Python 如何允许f()取十进制值
首先,我需要将学生分数相加,然后再将其转换为百分比。因此,我设法总结了他们的分数,并设法通过这种方法将其转换为百分比Python 如何允许f()取十进制值,python,django,Python,Django,首先,我需要将学生分数相加,然后再将其转换为百分比。因此,我设法总结了他们的分数,并设法通过这种方法将其转换为百分比 students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance'), percentage=(F('mark')/1100) * 100) 但是,我意识到F()不接受十进制值。它只接受整数值。如果值“mark”小于100,这将导致百分比计算出错 例如:600/1100=0.5
students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance'), percentage=(F('mark')/1100) * 100)
但是,我意识到F()不接受十进制值。它只接受整数值。如果值“mark”小于100,这将导致百分比计算出错
例如:600/1100=0.54545,则只需0乘以100即可。输出“0”而不是54%
如何允许函数取十进制值
编辑:
def file_load_view(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="studFinal-attendance.csv"'
writer = csv.writer(response)
writer.writerow(['Student Name', 'Attendance'])
students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance'),
percentage=(Cast('mark', FloatField())/1100) * 100)
#convert the students query set to a values list as the writerow expects a list/tuple
students = students.values_list('studName__VMSAcc','percentage')
for student in students:
writer.writerow(student)
return response
您可以使用来指定应将其转换为何种类型,从而让Django进行推断:
from django.db.models import FloatField
from django.db.models.functions import Cast
students = MarkAtt.objects.values('studName__VMSAcc').annotate(
mark=Sum('attendance'),
percentage=(Cast('mark', FloatField())/1100) * 100
)
从django.db.models导入FloatField
从django.db.models.functions导入强制转换
students=MarkAtt.objects.values('studName\uu VMSAcc')。注释(
马克=总和(“出席人数”),
百分比=(强制转换('mark',FloatField())/1100)*100
)
您可以将其转换为末尾的十进制字段,以使用特定位数:
from django.db.models import DecimalField, FloatField
from django.db.models.functions import Cast
students = MarkAtt.objects.values('studName__VMSAcc').annotate(
mark=Sum('attendance'),
percentage=Cast(
(Cast('mark', FloatField())/1100) * 100,
output_field=DecimalField(max_digits=20, decimal_places=2)
)
)
从django.db.models导入十进制字段、浮点字段
从django.db.models.functions导入强制转换
students=MarkAtt.objects.values('studName\uu VMSAcc')。注释(
马克=总和(“出席人数”),
百分比=铸件(
(铸造('mark',FloatField())/1100)*100,
输出字段=小数字段(最大位数=20,小数位数=2)
)
)
@Puteri:如果我用样本数据在本地运行这个程序,我会得到students.first()['percentage']
作为值Decimal('0.09')
。你能看看你得到的百分比吗?模板显示54.5%,而导出的数据显示54.5454。你介意看看我的另一个问题吗: