Django:将日期保存到数据库

时间:2019-03-14 05:27:14

标签: python django

我正在尝试将日期保存到考勤系统的数据库中。打印语句可以正常工作,但是日期不会保存到数据库中。 请帮忙。

models.py

class Attendance(models.Model):
    last_here = models.DateTimeField()


class Student(models.Model):
    student_name = models.CharField(max_length=200)
    student_gender = models.CharField(max_length=3, choices=GENDER, default='N/A')
    student_parent_email = models.EmailField()
    attendance = models.ForeignKey(Attendance, on_delete=models.CASCADE, default=1)

views.py

while(num!=amount): #there are multiple students.
    stu = Student.objects.filter(squad='LearnToSwim1')[num]

    if request.POST.get(stu.student_name, '') == 'on':
        stu.attendance.last_here = datetime.today() #this does not work.

        print("Student attendance taken")
        print(stu.attendance.last_here) 

        stu.save()


    num += 1

1 个答案:

答案 0 :(得分:1)

您必须保存Attendance模型,而不是Student模型,即stu.attendance.save() 即:

while(num!=amount): #there are multiple students.
    stu = Student.objects.filter(squad='LearnToSwim1')[num]

    if request.POST.get(stu.student_name, '') == 'on':
        stu.attendance.last_here = datetime.today() #this does not work.

        print("Student attendance taken")
        print(stu.attendance.last_here) 

        stu.attendance.save() # here


    num += 1