我正在尝试使用Django中的m2m_changed信号来创建有关“喜欢”帖子的通知。现在,我有一个post_save信号,用于创建评论通知。在我的m2m_changed信号函数中,在帖子pre_add和post_add上打印喜欢的查询集,表示发送信号后喜欢该帖子的用户的添加,即 pre = QuerySet [用户:TestUser]和 post = QuerySet [用户:TestUser,用户:test_user]。
我可以对instance.likes调用什么方法来返回与此m2m_changed信号关联的用户?还是可以在前后查询集上调用diff方法以返回此用户?我想通过
创建通知Notification.objects.create(post = instance,user = ?????,like = True,date_posted = ?????)
而且,有没有一种方法可以将通知的date_posted设置为等于发送信号的日期时间?
class Notification(models.Model):
post = models.ForeignKey('photo_blog.Post', on_delete=models.CASCADE, null=True, blank=True)
comment = models.ForeignKey(Comment, on_delete=models.CASCADE, null=True, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
liked = models.BooleanField(default=False)
date_posted = models.DateTimeField(null=True, blank=True)
@receiver(post_save, sender=Comment)
def auto_create_comment_notification(sender, instance, created, **kwargs):
if created:
Notification.objects.create(post=instance.post, comment=instance, date_posted=instance.date_posted)
@receiver(m2m_changed, sender=Post.likes.through)
def auto_create_like_notification(sender, instance, action, **kwargs):
if action == "pre_add":
print(instance.likes.all())
if action == "post_add":
print(instance.likes.latest())
我的帖子模型如下:
class Post(models.Model):
photo = models.ImageField(upload_to=get_image_path, null=True, blank=True)
caption = models.TextField(max_length=2200, null=True, blank=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
location = models.CharField(max_length=100, blank=True)
likes = models.ManyToManyField(User, blank=True, related_name='post_likes')
def __str__(self):
return self.caption
def get_absolute_url(self):
return reverse('photo_blog-detail', kwargs={'pk': self.pk})
def get_api_like_url(self):
return reverse('photo_blog-post_like_api', kwargs={"pk": self.pk})
def save(self):
super().save()
img = Image.open(self.photo.path)
output_size = (450, (img.height / img.width) * 450)
img.thumbnail(output_size)
img.save(self.photo.path)