我正在开发一个通知系统,该系统可以让学生知道他们累积十分或以上的分数。我正在处理几个if语句-一个用于检查分数是否大于等于10,另一个用于检查该学生本学期是否已收到10分以上的通知。如果他们尚未收到此通知,则将其发送出去。我遇到的问题是这样一个场景:一个学生得到10分,并收到通知,提出一些上诉,并删除了几分(因此他们回到10分以下),然后又累积了10分以上。他们第二次超过十时,不会发出通知,因为先前已经发出了通知,因此第二条if语句的计算结果为false。
我尝试在原始的if语句中添加or语句,以检查学生之前是否已收到通知,发送日期是今天之前。但是,我不太了解日期时间,也不确定如何执行此操作。我还尝试删除了if语句,该语句检查一个是否已经发出,但是这会导致一个事件的多个事件发生,而该事件的学生得分为10分以上。
notification_check.py:
def check_for_point_triggered():
def current_semester():
return AcademicTerm.objects.filter(date_end__gte=timezone.now(),
date_start__lte=timezone.now()
).order_by('date_end', '-date_start')[0]
emps_to_check = Employee.objects.that_have_active_points()
try:
ten_pts_template = NotificationTemplate.objects.get(
name="10 Points")
signature = NotificationSignature.objects.get(
name="AutoSignature")
except ObjectDoesNotExist as e:
raise CommandError(e)
for emp in emps_to_check:
points = emp.discipline_points()
# Check the 10 points template
if points >= 10:
if not emp.notificationrecord_set.filter(points__gte=10, semester=current_semester()):
# Need to send an expiration notification
notification = Notification(
sender=User.objects.get(username="mailer"),
title=ten_pts_template.title,
template=ten_pts_template,
signature=signature,
date_created=timezone.now(),
trigger='P'
)
notification.save()
notification.employee_recepients.add(emp)
notification.staff_recepients.add(*emp.supervisors())
try:
notification.staff_recepients.add(
User.objects.get(username='schaf1ka'))
except Exception:
print "Error adding user schaf1ka to 10 point email"
# Now to create a record
record = NotificationRecord(
employee=emp,
notification=notification,
email_text=notification.build_emails()[0].body,
points=points,
semester=current_semester(),
date_notified=timezone.now(),
)
record.save()
# Now to create automatic dismissal
EmployeeDismissal.objects.create(employee=emp,
date_dismissed=datetime.today())
models.py
class Notification(models.Model):
"""
Deconstructed email parts allows for reconstruction.
Record will be stored in NotificationRecord table.
Contains methods to build EmailMessage classes.
"""
title = models.CharField(
max_length=100, default="UREC Message", db_index=True)
sender = models.ForeignKey(User)
# Recepients
employee_recepients = models.ManyToManyField(Employee, blank=True)
staff_recepients = models.ManyToManyField(
User, related_name='staff_recepients', blank=True)
emp_groups = models.ManyToManyField(
EmploymentGroup, related_name='employee_groups', blank=True,
verbose_name="Employee Groups")
send_to_all_employees = models.BooleanField(default=False)
# Email Pieces
template = models.ForeignKey(NotificationTemplate, blank=True, null=True)
signature = models.ForeignKey(NotificationSignature, blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
date_sent = models.DateTimeField(null=True)
body = models.TextField(blank=True)
perf_report = models.ForeignKey(PerformanceReport, blank=True, null=True)
emp_cert = models.ForeignKey(EmployeeCertification, blank=True, null=True)
trigger = models.CharField(
max_length=1, choices=NOTIFICATION_TYPES, null=True)
# String of recepient names for recent notifications admin view
def recepient_names(self):
employees = ', '.join(
[a.global_id for a in self.employee_recepients.all()])
staff = ', '.join(
[a.username for a in self.staff_recepients.all()])
if staff:
return staff + ", " + employees
return employees
recepient_names.short_description = "Recipients"
def set_sent_flag(self):
if not self.date_sent:
a = self
a.date_sent = timezone.now()
a.save()
# Returns a list of emails. Will only be 1 email if it has no template
def build_emails(self):
"""
Returns a list of EmailMessages. Will be 1 bcc'd EmailMessage
if no template is found.
"""
email_messages = []
# Append employees in groups to employee recepients
for group in self.emp_groups.all():
emps = group.employees()
for emp in emps:
self.employee_recepients.add(emp)
# Add all employees if checked
if self.send_to_all_employees:
for emp in Employee.objects.filter(category=Category.objects.get(name="Active")):
self.employee_recepients.add(emp)
if self.template:
translated_template = Template(self.template.translate_tags())
for person in self.employee_recepients.all():
custom_body = translated_template.render(Context({"employee": person,
"pr": self.perf_report, "ec": self.emp_cert}))
# Append body from form if it exists
if self.body:
custom_body = custom_body + "\n\n" + self.body
if self.signature:
custom_body = custom_body + "\n\n" + self.signature.body
# Append custom email to email list
message = EmailMessage(subject=self.template.title,
to=[person.global_id + "@cmich.edu"],
body=custom_body)
# If only one employee recepient, cc all of the staff
# recepients
if len(self.employee_recepients.all()) == 1:
message.cc = [x.username + "@cmich.edu" for x in self.staff_recepients.all()]
email_messages.append(message)
# No template found
if not self.template:
custom_body = self.body
if self.signature:
custom_body = self.body + '\n\n' + self.signature.body
email_messages.append(
EmailMessage(subject=self.title, body=custom_body,
cc=[x.global_id + "@cmich.edu" for x in self.employee_recepients.all()]))
return email_messages
def __unicode__(self):
return unicode(self.title + " " + self.date_created.strftime("%x %X"))
class NotificationRecordManager(models.Manager):
def one_month_back(self):
four_weeks = timezone.now() - timedelta(days=28)
return self.model.objects.filter(date_created__gt=four_weeks)
class NotificationRecord(models.Model):
"""
Constructed notification email to allow for duplicate searching.
Contains resolved template tags.
"""
employee = models.ForeignKey(Employee)
notification = models.ForeignKey(Notification)
certification = models.ForeignKey(
EmployeeCertification, blank=True, null=True)
dismissal = models.ForeignKey(EmployeeDismissal, blank=True, null=True)
discpoints = models.ForeignKey(EmployeeDiscipline, blank=True, null=True)
email_text = models.TextField(db_index=True)
points = models.IntegerField(default=0)
semester = models.ForeignKey(AcademicTerm, blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
objects = NotificationRecordManager()
def __unicode__(self):
return unicode(unicode(self.employee) + unicode(self.date_created))