pre_delete我正在尝试为我的 Django 应用程序模型使用信号Like。该Like模型有一个Book外键。该Book模型有一个num_of_likes字段。最终,我试图num_of_likes从我的信号中更新这个字段pre_delete。只是我做不到。我的代码会让问题是什么变得非常清楚,我想(请特别注意注释和打印语句):书籍/模型.py:class Book(models.Model): num_of_likes = models.IntegerField()喜欢/ models.py:class Like(models.Model): user = models.ForeignKey(User) book = models.ForeignKey(Book)喜欢/views.py:class DeleteLikeView(APIView): def post(self, request, book): book = get_object_or_404(Book, id=book) print(book.num_of_likes) # Prints, say, 10 like = Like.objects.get(user=request.user, book=book) like.delete() # triggers signal handler below (should update `book.num_of_likes`) print(book.num_of_likes) # Still prints 10, expected 9 <------ PROBLEM return ...喜欢/信号.py:@receiver(pre_delete, sender=Like)def delete_book_like(sender, instance, **kwargs): print(instance.book.num_of_likes) # Prints 10 instance.book.num_of_likes -= 1 instance.book.save() print(instance.book.num_of_likes) # Prints 9, as expected为什么book.num_of_likes内部得到更新delete_book_like但更改却没有显示在 中DeleteLikeView?
1 回答
qq_笑_17
TA贡献1818条经验 获得超7个赞
book删除视图中的 是与信号处理程序中不同的Python对象。instance.bookPython 对象不会神奇地了解到底层数据库表示已更改。您可以refresh_from_db在打印前调用:
book.refresh_from_db()
print(book.num_of_likes)
或者只是创建num_of_likes一个动态评估的属性,您不必担心非规范化数据的完整性:
class Book(models.Model):
@property
def num_of_likes(self):
return self.like_set.count()
添加回答
举报
0/150
提交
取消