简体   繁体   English

Django如何使用post_save信号

[英]Django how to use post_save signals

I had learn about django signals but, I don't known where to implement in my project and how to use it in my project. 我已经了解了django信号但是,我不知道在我的项目中实现的位置以及如何在我的项目中使用它。 In my project I want send email alerts if it matches to some particular criteria. 在我的项目中,我想发送电子邮件警报,如果它符合某些特定标准。 In this case I need use post_save signals.I added the code with this. 在这种情况下,我需要使用post_save信号。我添加了代码。 Kindly share your ideas. 请分享您的想法。

models.py models.py

class Personal(models.Model):
    user = models.OneToOneField(User)
    email = models.EmailField(max_length=100, blank=True, null=True)
    country = models.CharField(max_length=100, blank=True, null=True)
    state = models.CharField(max_length=100, blank=True, null=True)
    city = models.CharField(max_length=100, blank=True, null=True)

class Skills(models.Model):
    user = models.ForeignKey(User)
    skill = models.CharField(max_length=100, blank=True, null=True)

class jobs(models.Model):
    emp = models.ForeignKey(User, unique=False)
    title = models.CharField(max_length=100)
    industry = models.CharField(max_length=100)
    functionalarea = models.CharField(max_length=100)
    min_exp = models.IntegerField(default=0)
    max_exp = models.IntegerField(default=0)
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=100)
    country = models.CharField(max_length=100)
    empskills = models.CharField(max_length=100, blank=True, null=True)

Here I want to match city and empskills of jobs table with personal.city and Skills.skill model. 在这里,我希望将jobs和empills.skill模型匹配city和empskills of jobs表。 This event occurs every job posting if it matches any one field it will send mail to personal.email automatically. 如果每个作业都匹配任何一个字段,它将自动发送邮件到personal.email,则会发生此事件。 Please give sample one where and how to use the signal. 请举例说明信号的使用位置和使用方法。

Write a function outside the model that handles when a new job is posted and finds the people to email. 在模型外部编写一个函数,用于处理发布新作业的时间并找到要发送电子邮件的人员。

You then specify Job as the sender for a post_save signal and connect the function. 然后,您将Job指定为post_save信号的sender并连接该功能。

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Job)
def handle_new_job(sender, **kwargs):
    job = kwargs.get('instance')
    logger.info("POST_SAVE : Job : %s" % job)
    # find people to email based on `job` instance

This is an example of how to use post_save 这是如何使用post_save的示例

from django.db.models.signals import post_save
from .models import MyModel

def my_handler(**kwargs):
    if kwargs[’raw’]:
        return
    ...
    # here you could return your mails 
post_save.connect(my_handler, sender=MyModel)

Hope this could help you ! 希望这可以帮到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM