我想制作一个基于Django的音乐库。所以,我有基本的歌曲模型,专辑在' shop'用户收集的应用和复制模型。我想知道,当用户创建某个专辑的副本时,有没有办法添加与专辑相关的歌曲?
商店应用的基本型号:
class Album(models.Model):
artist = models.ForeignKey(Artist)
name = models.CharField(max_length=128)
year = models.IntegerField(default=timezone.now().year)
genre = models.ForeignKey(Genre)
songs = models.ManyToManyField('Song', blank=True)
cover = models.ImageField(upload_to=cover_album_directory_path)
is_single = models.BooleanField()
is_ep = models.BooleanField()
is_compilation = models.BooleanField()
def __str__(self):
return self.name
class Song(models.Model):
artist = models.ForeignKey(Artist)
related_album = models.ForeignKey(Album)
album_position = models.IntegerField()
name = models.CharField(max_length=128)
lyrics = models.TextField(blank=True)
track = models.FileField(upload_to=song_directory_path)
def __str__(self):
return self.name
专辑和歌曲副本的模型:
class CopyAlbum(models.Model):
owner = models.ForeignKey(Library)
album = models.ForeignKey(Album, blank=True)
def __str__(self):
return self.album.name
class CopySong(models.Model):
owner = models.ForeignKey(Library)
song = models.ForeignKey(Song, blank=True)
def __str__(self):
return self.song.name
我真正需要的是:在创建复制专辑后,Django必须自动保存与专辑相关的copysongs。
感谢您的帮助。
答案 0 :(得分:1)
您可以使用信号。
在CopyAlbum,CopySong模型文件中:
from django.db.models.signals import post_save,post_delete
from django.dispatch import receiver
@receiver(post_save,sender=CopyAlbum)
def copy_songs(*args,**kwargs):
copy_album_instance = kwargs['instance']
... copy the songs ...
@receiver(post_delete,sender=CopyAlbum)
def delete_songs(*args,**kwargs):
copy_album_instance = kwargs['instance'] ## deleted, an instance w/o db record
... delete the songs ...