I am trying to create a School Attendance Module and I have a StudentClass table, the Student table, Attendance table and the AttendanceRecord table. Here is the code
class StudentClass(models.Model):
name = models.CharField(max_length=100)
# stream = models.ForeignKey('Stream', on_delete=models.PROTECT)
creation_date = models.DateTimeField(auto_now=False, auto_now_add=True)
def __str__(self):
return self.name
class Student(models.Model):
name = models.CharField(max_length=100)
klass = models.ForeignKey('StudentClass', models.PROTECT, related_name='students')
def __str__(self):
return self.name
class Attendance(models.Model):
date = models.DateTimeField(auto_now_add=True)
klass = models.ForeignKey('StudentClass', models.PROTECT, related_name='attendances')
def save(self, *args, **kwargs):
if self.records.count() <= 0:
for student in self.klass.students.all():
self.records.create(student=student, status='present')
super(Attendance, self).save(*args, **kwargs)
def __str__(self):
return f"{self.id}, {self.date}"
class AttendanceRecord(models.Model):
ATTENDANCE_STATUS = [
('present', 'PRESENT'),
('absent', 'ABSENT')
]
attendance = models.ForeignKey(
'Attendance',
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name='records'
)
student = models.ForeignKey('Student', on_delete=models.PROTECT)
status = models.CharField(max_length=100, choices=ATTENDANCE_STATUS)
def __str__(self):
return f"(STUDENT: {self.student}, STATUS: {self.status})"
What am I trying to achieve??
I want to have a situation whereby when I trigger the creation of a Attendance instance an Attendance Record linked to that instance is generated with the record generating default attendance records for all students enrolled in that klass with a default attendance status of present which I can get on to edit only for those students who are absent. The method I tried for ovveriding the save method didnt work as it generated this error ' "unsaved related object '%s'." % field.name
ValueError: save() prohibited to prevent data loss due to unsaved related object 'attendance'.'
I wasnt really confident of that solution anyway.
May you assist me on how best one wld solve such a problem
Thank you in Advance
Dumba
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2742a034-586d-44a2-872a-5d0c24dc8d70n%40googlegroups.com.
No comments:
Post a Comment