Django中的后台进程



我是Django的大一新生,在理解实现后台过程方面遇到了问题。例如,我有:

型号.py

class Person(models.Model):
name = models.CharField(max_length=23)
math_grade = models.IntegerField(null=True, blank=True)
phys_grade = models.IntegerField(null=True, blank=True)
avg_grade = models.IntegerField(null=True, blank=True)

class PersonAdmin(admin.ModelAdmin):
list_display=('name', 'math_grade ','phys_grade', 'avg_grade')

管理员.py

from django.contrib import admin
from .models import *
admin.site.register(Person, PersonAdmin)

如何实现下一件事:自动(定期(检查math_grade和phys_grade是否保存到该人员的数据库中,然后自动将avg_grade保存为(a+b(/2

您不需要为其定期运行代码。当您拥有两个数字时,只需要更新avg_grade。因此,当您通过请求获得两个数字时,只需计算avg_grade即可(否则,您将如何更新标记(以下代码将帮助您进一步处理。

from django.http import HttpResponse
from django.views import View
class UpdateAvgGrade(View):
def post(self, request):
data = request.data
math_marks = data.get('math_marks')
phy_marks = data.get('phy_marks')
name_of_person = data.get('name') # as your Person model don't have a User. So using Name to fetch exact user.
person = Person.objects.get(name=name_of_person)
if person.math_marks == None:
# if there are no math_marks present then save math_marks to math_marks from request.
person.math_marks = math_marks
person.save()
if person.phy_marks == None:
# same thing as math_marks for phy_marks.
person.phy_marks = phy_marks
person.save()
math_marks = person.math_marks # updading this in case you get only value from request and other is present already in DB.
phy_marks = person.phy_marks
# now calculate the average grade.
if person.avg_grade == None:
# check if you are getting both math and phy marks from request.
# is yes then you can find the average grade.
if math_marks and phy_marks:
avg_grade = (math_marks + phy_marks) // 2 # becase it is int field.
else:
return HttpResponse({
'msg': 'Please provide both math and phy marks.'
})
else:
return HttpResponse({
'msg': 'avg_grade already present and not udpated.'
})

最新更新