Reputation: 233
I am a freshman in Django and I have a problem with understanding of implementation background processes. For example, I have:
model.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')
admin.py
from django.contrib import admin
from .models import *
admin.site.register(Person, PersonAdmin)
How to implement the next thing: Automatically check (periodically) if math_grade and phys_grade are saved into the DB for this Person, and then automatically f.e. save avg_grade as (a+b)/2
Upvotes: 0
Views: 140
Reputation: 1242
you don't need to run your code periodically for it. you need to just update the avg_grade
when you have both the number. so just calculate the avg_grade
when you have both number through a request(else how ll you update the marks.)
Following code should help you to process further.
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.'
})
Upvotes: 1