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?
qq_笑_17
相关分类