Chidananda Nayak
Chidananda Nayak

Reputation: 1201

Unresolved Error in Django Signal

I want to populate artistfield of Album model with pre_save function while saving an instance Musician model.

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()

But when I am trying to create an instance of Musician Model from admin, it shows this error upon hitting save button.

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

I cant understand how to solve this sm.save() error! Please be helping me.

Upvotes: 2

Views: 330

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

pre_save signal is calling before Musician instance saved to db. But you cannot set as artist value unsaved instance. You should change signal to post_save. In this case Musician will be saved at the moment album is creating:

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

Upvotes: 2

Related Questions