Django-级联的反向等效项是什么? [英] Django - What is the reverse equivalent of cascade?

查看:78
本文介绍了Django-级联的反向等效项是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个小型音乐数据库。学习SQL过去已经有很长的时间了,我一直想尝试一下django。但是有一件事我无法解决。

I am writing a small music database. Learning SQL lies quite a long time in my past and I always wanted to give django a try. But there is one thing I couldn't wrap my head around.

现在,我的模型仅包含两个类,相册 Song
歌曲具有指向其所属专辑的外键。现在,如果我删除该相册,则所有歌曲的所属都将由于级联而被删除。

Right now, my models only consist of two Classes, Album and Song. Song has a foreign key pointing to the album it belongs to. Now if I would delete that Album, all Songs "belonging" to it, would be deleted due to the cascading effect.

相册在我的数据库中有点虚,实际上只有歌曲在文件系统上表示,而专辑是根据songs标签构造的,所以我只能知道如果没有更多歌曲指向该专辑,该专辑将不存在(因为它们不再存在于文件系统中)。

Albums are kinda virtual in my database, only songs are actually represented on the filesystem and the albums are constructed according to the songs tags, therefore I can only know an album doesn't exist anymore if there are no more songs pointing to it (as they no longer exist in the filesystem).

或者简而言之,我如何实现反向层叠,这意味着,如果没有更多的歌曲指向专辑,则该专辑也应删除吗?

Or in short, how can I achieve a cascade in reverse, that means, if no more songs are pointing to an album, the album should be deleted as well?

推荐答案

您可以使用预删除信号删除相册

You could use the pre-delete signal to remove the Album when a Song is deleted and there are no more songs.

from yourapp.models import Album, Song
from django.db.models.signals import pre_delete

def delete_parent(sender, **kwargs):
    # Here you check if there are remaining songs.
    ....

pre_delete.connect(delete_parent, sender=Song)

这篇关于Django-级联的反向等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆