在Django中修改数据库

时间:2018-07-07 17:51:19

标签: django database save views

我是django的初学者。以下是我的出勤管理应用程序。 这是我的models.py。

from django.db import models

class Subject(models.Model):
    subject_name = models.CharField(max_length=20)
    #attendance = models.ForeignKey(Attendance, on_delete = 
    models.DO_NOTHING)
    attendance = models.IntegerField(default=0)
    def __str__(self):
        return self.subject_name


class Section(models.Model):
    section_name = models.CharField(max_length=20)
    subject = models.ManyToManyField(Subject)
    def __str__(self):
        return self.section_name


class Student(models.Model):
    rollno = models.IntegerField()
    name = models.CharField(max_length=20)
    section = models.ForeignKey(Section, on_delete = models.DO_NOTHING, 
    default=0)
    def __str__(self):
        return str(self.rollno) + self.name 


class Teacher(models.Model):
    #teacher_name = models.CharField(max_length=20)
    section = models.ForeignKey(Section, on_delete=models.CASCADE)
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
    #section_name = models.CharField(max_length=10)
    #subject_name = models.CharField(max_length=30)
    def __str__(self):
        return self.section.section_name+' '+self.subject.subject_name


class TeacherList(models.Model):
    teacher_name = models.CharField(max_length=20)
    teacher = models.ManyToManyField(Teacher)
    def __str__(self):
        return self.teacher_name

下面的行在views.py中不起作用

student = models.Student.objects.get(rollno = sroll)
student.section.subject.get(subject_name = 'java').attendance += 1
student.save()

单击按钮以添加学生的出勤率时,将从模板中调用此视图。 上面代码中的出勤没有修改。请帮帮我。

1 个答案:

答案 0 :(得分:2)

您要保存的是学生,而不是主题。

student = models.Student.objects.get(rollno = sroll)
subject = student.section.subject.get(subject_name='java')
subject.attendance += 1
subject.save()

或者更好的是,一次性完成更新:

student.section.subject.filter(subject_name='java').update(attendance=F('attendance')+1)

,根本不需要保存。