Search code examples
djangodjango-modelsdjango-signals

Connecting Foreign key models with Django signal


I'm trying to build a Django signal whose sender is a Model (called Bacteria) and whose receiver is a model (called Bumblebee). These models have a foreign key relationship through the following:

class Bumblebee(models.Model):
    name = models.CharField(max_length=50)

class Bacteria(models.Model):
    bumblebee = models.ForeignKey(Bumblebee, on_delete=models.CASCADE) 

When I'm building this post_save signal to listen for a Bacteria being created, how do I then call fields of Bumblebee? This is what I have but it's not working.

@receiver(post_save, sender=Bacteria)
def my_handler(sender, **kwargs):
    bumblebee = Bacteria.bumblebee
    print(bumblebee.name)

Solution

  • You need to use the currently created instance of Bacteria.

       @receiver(post_save, sender=Bacteria)
       def my_handler(sender,instance,created,**kwargs):
         if created:
            bumblebee = instance.bumblebee
            print(bumblebee.name)
    

    Here instance is the object of Bacteria.