i have a model A which has a many to one relationship with another model B,i want to be able to get send an email notification to emails which will be queried from model B any time values change in model A how can i do that in django?
class ModelA(models.Model):
"""
model to store informations about the ModelA
"""
name = models.CharField(max_length=15, blank=True, unique=True)
creator = models.ForeignKey(AppUser, blank=True, null=True, on_delete=models.CASCADE)
periodicity = models.CharField(max_length=10, blank=False, choices=PERIODICITY_CHOICES)
begin_date = models.DateField(blank=False)
end_date = models.DateField(blank=True, null=True)
subscription_fee = models.DecimalField(max_digits=5, decimal_places=2, blank=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
public = models.BooleanField(default=False)
maximum_sub = models.PositiveIntegerField(blank=True, null=True, validators=[MinValueValidator(2)])
def save(self):
emails = []
body = """
Hello <user first name or nothing>,
This is to notify you that ModelA you're subscribed to has been updated. Here is what has changed:
<field_name_1>: <current_value>
<field_name_2>: <current_value>
etc...
Thank you
"""
if self.pk is not None:
modelA_id = ModelA.objects.get(pk=self.pk)
modelA_members = ModelB.objects.filter(pk=modelA_ID)
emails = [i for i in modelA_members.email]
send_mail('ModelA change Notification', body, "noreply@example.com", [emails])
super(ModelB, self).save() #
def __unicode__(self):
return u'{0}'.format(self.name)
class ModelB(models.Model):
"""
defineModelB
"""
modelA = models.ForeignKey(ModelA, on_delete=models.CASCADE, blank=False)
user = models.ForeignKey(AppUser, on_delete=models.CASCADE, blank=False, )
cash_out_date = models.DateField(blank=True, null=True)