We have two model class: Student and Instructor. Student and Instructor have one to many relationship.
Models:
class Student(models.Model):
instructor = models.ForeignKey(Board, on_delete=models.CASCADE, related_name="students")
name = models.CharField(max_length=255)
roll = models.IntegerField()
mark = models.DecimalField(decimal_places=8, max_digits=16, default= 0.0)
class Instructor(models.Model):
name = models.CharField(max_length=255)
Serializers:
class StudentSerializer(serializers.ModelSerializer):
class Meta:
fields = ('id', 'name', 'roll', 'mark')
model = Student
class InstructorSerializer(serializers.ModelSerializer):
students = StudentSerializer(many=True, read_only=True)
class Meta:
fields = ('id', 'name', 'students')
model = Instructor
We have a hypothitical scenario where instructor wants to increase each students marks with a crazy formula: student's ranking * 2
. That means, we have to update each of the student table's row for that corresponding teacher id.
For example:
there are 3 students -
Student 1: ( name: "A", roll: 3, mark: 10) ;
Student 2: ( name: "B", roll: 4, mark: 15) ;
Student 3: ( name: "B", roll: 4, mark: 13) ;
after operation:
Ranking of the students by marks :
Student 2 ( Rank 1), Student 3 ( rank 2 ), Student 1 ( rank 3).
Student-2(Rank-1)'s mark will be increase as follows ( 1 * 2 ),
Student-3(Rank-2)'s mark will be increase as follows ( 2 * 2 ),
Student-3(Rank-3)'s mark will be increase as follows ( 3 * 2 )
I had tried to do something like the following -
Student.objects.filter(instructor=instructor_ID).order_by('order').update(mark = F('mark') 2 )
This way simply add 2 to each of the students. But we wanted to increase marks with the above mentioned formula that is - student's ranking * 2
. Could you please help me achive this in django ?
CodePudding user response:
Try this:
all_students=Student.objects.filter(instructor=instructor_ID).order_by('order')
for i, val in enumerate(all_students):
val.mark = (i 1)*2)
val.save()
Output will be:
Student 1(...other fields, mark=2)
Student 2(... Other fields, mark=4)
Student 3(... Other fields, mark=6)