我有以下型号:
class Grade(models.Model):
grade = models.CharField(max_length=255, unique=True)
class Student(models.Model):
class Meta:
unique_together = ("rollno", "grade")
name = models.CharField(max_length=255)
grade = models.ForeignKey(Grade,related_name='StudentList', on_delete=models.CASCADE)
rollno = models.BigIntegerField(unique = True)
class GradeTotal(models.Model):
grade = models.ForeignKey(Grade, related_name='GradeMarks', on_delete=models.CASCADE)
average = models.IntegerField()
total = models.IntegerField()
class StudentTotal(models.Model):
rollno = models.ForeignKey(Student, related_name='StudentMarks', on_delete=models.CASCADE)
gradeno = models.ForeignKey(GradeTotal, related_name='Fromgrade', on_delete=models.CASCADE)
marks = models.IntegerField()
我正在使用模型Grade
创建GradeTotal
,然后创建StudentTotal
。仅当StudentTotal
和grade
的外键GradeTotal
与用于该过程的Student
的瞬间相同时,才创建对象Grade
。
为此,我需要以下序列化程序:
class StudentDataSerializer(serializers.ModelSerializer):
rollno = serializers.CharField()
class Meta:
model =StudentTotal
fields = ('marks', 'rollno' )
class GradeSerializer(serializers.ModelSerializer):
Fromgrade = StudentDataSerializer(many=True)
class Meta:
model = GradeTotal
fields = ('average', 'total', 'Fromgrade', )
class MultipleGradeSerializer(serializers.ModelSerializer):
GradeMarks = GradeSerializer(many=True)
grade = serializers.CharField()
class Meta:
model = Grade
fields = ("grade", "GradeMarks")
def update(self, instance, validated_data):
g_data = validated_data.pop('GradeMarks')
for datas in g_data:
a1 = datas["average"]
t1 = datas["total"]
g1 = GradeTotal.objects.create(grade=instance, average=a1, total=t1)
data2 = datas.pop('Fromgrade')
for data in data2:
e1 = data["rollno"]
r1 = Student.objects.get(rollno=data["rollno"])
if s1.grade == instance:
StudentTotal.create(gradeno = g1, rollno = r1, marks =data["marks"])
return instance
这是我能想到的最好的方法,但是通过以下JSON有效负载来实现:
{
"grade": "nine",
"GradeMarks": [
{
"average": 10,
"total": 5,
"Fromgrade": [
{
"marks": 30,
"rollno": "N1 "
}
]
}
]
}
我收到以下错误:Student matching query does not exist
,但是我可以使用django admin查看带有rollno
N1的对象。我不确定为什么会这样。因此,我无法创建StudentTotal
的对象,但可以创建GradeTotal
。
在我看来,我使用Grade
作为模型,使用MultipleGradeSerializer
作为序列化器。任何帮助将不胜感激。
其他信息 如果我做以下调试工作
r1 = Student.objects.get(rollno="N1")
,我不知道此错误,但不知道为什么,但是出现以下错误:
type object 'StudentTotal' has no attribute 'create'.
第二期我已经看过this,我的观点已经有了mixins.CreateModelMixin
。此外,它创建对象GradeTotal
任何人都可以把这两点都清除吗?
答案 0 :(得分:0)
此行:
StudentTotal.create(gradeno = g1, rollno = r1, marks =data["marks"])
应为:
StudentTotal.objects.create(gradeno = g1, rollno = r1, marks =data["marks"])