I hope that the title of my message will be precise enough, if it is not the case I apologize in advance.
I do not know how to do the following thing:
I have two models:
the first one named Band
class Band(models.Model): ''' Model to manage band ''' name = models.CharField('Nom du Groupe', max_length=80, default='En cours de création', unique=True, ) bio = models.TextField("Courte description", max_length=500, blank=True) town = models.CharField("Ville", max_length=60, blank=True) avatar = models.ImageField(null=True, blank=True, upload_to='band_avatar/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) owner = models.OneToOneField(User, on_delete=models.PROTECT)
and the second one witch provides the members of the Band
class Member(models.Model): ''' Musicians of the band ''' member = models.ForeignKey(User, on_delete=models.CASCADE) band = models.ForeignKey(Band, on_delete=models.CASCADE)
How can I do the following thing?
The user creating the Band model must be added automatically as a member of the band (he is also the owner of the Band , cf : owner field).
I wonder if I should not add signals on the post save of the model Band? Like this :
class Member(models.Model): ''' Musicians of the band ''' member = models.ForeignKey(User, on_delete=models.CASCADE) band = models.ForeignKey(Band, on_delete=models.CASCADE) @receiver(post_save, sender=Band) def create_member(sender, instance, created, **kwargs): if created: Member.objects.create(member=instance.owner, band=instance) @receiver(post_save, sender=Band) def save_member(sender, instance, **kwargs): # some stuff
But I am disappointed by the use of the two foreign keys of my association table.
I thank you in advance for your lights!