如何从 usercusomer 获取关注者的电子邮件

How to get email from usercusomer for followers

我想在创建项目后向每个关注者发送一封电子邮件。但我不知道如何从模型中获取此字段,也不知道如何发送每个关注者以关联关注。

models.py

class Book(models.Models):
   title = models.CharField(max_length=255)
   author = models.ForeignKey(
        "users.CustomUser", on_delete=models.SET_NULL, null=True
    )
  
# This is my try
#But it doesn't work 
   @hook(AFTER_CREATE)
    def send_followers(self):
        user = Followers.objects.all()
        followers_email = CustomUser.objects.filter(
            followers__follower__in=, followers__following=self.author.profile)

        if CustomUser.objects.filter(
            followers__follower__in=CustomUser.objects.only(
                'followers__follower'),
            followers__following=self.author.profile
        ).exists():
            send_mail(
                "Article published",
                '%s' % (
                    followers_email
                ),
                "nikitaalexnazarov@yandex.ru",
                [self.author.email],
                fail_silently=False,
            )
        else:
            pass

class CustomUser(AbstractUser):
    gender = models.ForeignKey(
        "Gender", on_delete=models.CASCADE, blank=True, null=True
    )

class Followers(models.Model):
    follower = models.ForeignKey(
        "users.CustomUser", on_delete=models.CASCADE, null=True, blank=True)
    following = models.ForeignKey(
        "Profile", on_delete=models.CASCADE, null=True, blank=True)

class Profile(models.Model):
    slug = models.SlugField(unique=True)
    user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)

您的要求可以通过信号来满足。在 Django 中,信号用于根据某些事件执行某些操作。在您的情况下,您希望在创建新书时向作者的所有关注者发送电子邮件。发送邮件的代码可以在接收者中实现。 post_save 信号将在 Book 模型中创建新行时触发。相应的信号会被'send_mail'接收器接收并执行。

signals.py

from django.dispatch import receiver

@reciever(post_save, sender="Book")
def send_mail(sender, instance, **kwargs):

    # get the user model row of the author. Since author field is in M2One relationship with CustomUser, we can access the id of the user.
    user_obj = instance.author

    # ProFile model is in One2One relationship with CustomUser. Get the profile instance/row corresponding to the user_obj.
    profile_obj = user_obj.profile
    followers_list = Followers.objects.filter(following=profile_obj)
    #followers_list will be having a list of all the followers to whom mail can be sent. You can retrieve the email of the followers present in followers_list.

apps.py

from django.apps import AppConfig


class AppNameConfig(AppConfig):
    name = 'AppName'

    def ready(self):
        import signals over here