Django - pre_delete 信号不更新实例的外键字段

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?


心有法竹
浏览 104回答 1
1回答

qq_笑_17

book删除视图中的 是与信号处理程序中不同的Python对象。instance.bookPython 对象不会神奇地了解到底层数据库表示已更改。您可以refresh_from_db在打印前调用:&nbsp;book.refresh_from_db()&nbsp;print(book.num_of_likes)或者只是创建num_of_likes一个动态评估的属性,您不必担心非规范化数据的完整性:class Book(models.Model):&nbsp; &nbsp; @property&nbsp; &nbsp; def num_of_likes(self):&nbsp; &nbsp; &nbsp; &nbsp; return self.like_set.count()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python