如何解决将对象添加到另一个模型上的 ManyToMany 字段后如何调用 post_save 信号
我有两个模型,Post
和 Comment
。现在我有一个在 post_save
对象上使用 comment
信号的自定义函数。但是,由于我保存后将对象添加到多对多字段中,因此无法获取Parent post对象的属性。
所以我有:
comment.save()
post.comments.add(comment)
现在我有一个函数:
@receiver(post_save,sender=Comment)
def update_comment_count(sender,instance,**kwargs):
cache.set("post_comment_count_{}".format(instance.post.id),instance.post.comments.all().count())
但是,这不起作用,因为 post 对象还没有添加评论对象,有什么办法可以解决这个问题吗?
解决方法
您可以使用 m2m_changed
signal [Django-doc]:
from django.db.models.signals import m2m_changed
@receiver(m2m_changed,sender=Post.comments.through)
def comments_changed(sender,instance,action,**kwargs):
if action in ('post_add','post_remove','post_clear'):
cache.set(f'post_comment_count_{instance.pk}',instance.comments.count())
话虽如此,signals are typically anti-patterns。许多 ORM 调用可以绕过信号,并且它使保存对象的可预测性降低。因此,最好将逻辑简单地封装在视图中,然后在编辑注释的视图中调用该函数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。