Django, post_delete,使用反向关系安全吗?

时间:2022-09-11 18:25:56

Suppose Album has Songs.

假设专辑歌曲。

When songs are deleted, I 'd like to update the song count of album objects.
(Let's just assume that we store the count of songs in Database field)

当歌曲被删除时,我想更新专辑对象的歌曲计数。(假设我们将歌曲的计数存储在数据库字段中)

Is it safe to do

这样做安全吗

@receiver(post_delete, sender=Song)
def set_song_count(sender, song, **kwargs):
  song.album_set.update_song_count()

Song has ForeignKey to Album. No M2M involved.

这首歌有外国人的专辑。涉及任何M2M。

1 个解决方案

#1


1  

No, it's not safe. From the documentation:

不,它不是安全的。从文档:

Note that the object will no longer be in the database, so be very careful what you do with this instance.

注意,对象将不再位于数据库中,所以要非常小心地处理这个实例。

The instance has gone from the database by this point. Trying to fetch song.album_set will (unless it has been prefetched elsewhere, which you cannot rely on) trigger a database query for objects related to this one. I don't think you will get an error, but because the object no longer exists in the database, you will simply get an empty result.

此时,实例已经从数据库中取出。试图获取歌曲。album_set将(除非它已经被预取到其他地方,您不能依赖它)触发与此对象相关的数据库查询。我认为您不会得到错误,但是由于对象不再存在于数据库中,您将得到一个空结果。

You could consider using the pre_delete signal to run some code that decrements the count for the associated albums. You could also do this in a delete method on the model itself.

您可以考虑使用pre_delete信号来运行一些代码,以减少相关相册的计数。您还可以在模型本身的delete方法中执行此操作。

#1


1  

No, it's not safe. From the documentation:

不,它不是安全的。从文档:

Note that the object will no longer be in the database, so be very careful what you do with this instance.

注意,对象将不再位于数据库中,所以要非常小心地处理这个实例。

The instance has gone from the database by this point. Trying to fetch song.album_set will (unless it has been prefetched elsewhere, which you cannot rely on) trigger a database query for objects related to this one. I don't think you will get an error, but because the object no longer exists in the database, you will simply get an empty result.

此时,实例已经从数据库中取出。试图获取歌曲。album_set将(除非它已经被预取到其他地方,您不能依赖它)触发与此对象相关的数据库查询。我认为您不会得到错误,但是由于对象不再存在于数据库中,您将得到一个空结果。

You could consider using the pre_delete signal to run some code that decrements the count for the associated albums. You could also do this in a delete method on the model itself.

您可以考虑使用pre_delete信号来运行一些代码,以减少相关相册的计数。您还可以在模型本身的delete方法中执行此操作。