Django Signal中未解决的错误

时间:2018-06-30 17:04:35

标签: python django

我要在保存实例artist模型的同时使用Album函数填充pre_save模型的Musician字段。

models.py

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

    def __str__(self):
        return self.first_name



class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField(null=True,blank=True)
    num_stars = models.IntegerField(null=True,blank=True)

    def __str__(self):
        return self.artist

@receiver(pre_save,sender = Musician)
def create_album(sender,instance,**kwargs):
    sm = Album()
    sm.artist = instance
    sm.save()

但是,当我尝试从admin创建Musician Model的实例时,点击保存按钮时会显示此错误。

Exception Type: ValueError at /admin/sig/musician/add/
Exception Value: save() prohibited to prevent data loss due to unsaved related object 'artist'.

我无法理解如何解决此sm.save()错误!请帮助我。

1 个答案:

答案 0 :(得分:2)

pre_save信号正在调用之前 Musician实例保存到数据库。但是您不能将未保存的实例设置为艺术家值。您应该将信号更改为post_save。在这种情况下,音乐人将在创建专辑时保存:

@receiver(post_save,sender = Musician)
def create_album(sender,instance,**kwargs):
    sm = Album()
    sm.artist = instance
    sm.save()