// signals.py
@receiver(pre_save, sender=AcademicLesson)
def take_attendance(sender, instance, **kwargs):
new_file = instance.class_img
if new_file:
sub = instance.sub_id
# this for loops gives all student from each branch having comman subject(sub = instance.sub_id)
for branch in sub.universitybranch_set.all():
for std in branch.studentprofile_set.all():
if std.profile_encode: # for understanding, student present or not
print('-------------------------added')
instance.student.add(std)
else:
print('---------------------not-added')
print('no. of student=', len(instance.student.all()))
# // models.py
class AcademicLesson(models.Model):
date = models.DateField()
sub_id = models.ForeignKey('UniversitySubject', on_delete=models.CASCADE, limit_choices_to={'is_elect': True})
class_type = models.CharField(max_length=7, choices=[('lecture','Lecture'),('lab','Lab')])
slot = models.CharField(max_length=1, choices=[('1','1'),('2','2'),('3','3'),('4','4'),('5','5'),('6','6')])
class_img = models.ImageField(upload_to=path_to_upload_media, blank=True)
student = models.ManyToManyField('StudentProfile', blank=True)
def __str__(self):
return f"{self.date} | {self.sub_id}"
class Meta:
verbose_name = 'Academic Lesson'
当我用 django shell 验证时,它返回 <QuerySet []>
lesson = AcademicLesson.objects.get(date='2021-04-05')
lesson.student.all()
我尝试了什么。
- 覆盖 models.Model.save 方法,但会出现同样的问题。
- forms.ModelForm 不适合我们的项目
如果我在 django shell 中运行 signals.py 中显示的代码,那么它可以正常工作,但是相同的逻辑在 signals.py 中不起作用
我哪里做错了?