Search code examples
djangodjango-modelsdjango-viewsdjango-formsdjango-signals

Django cannot update second field with signal


When i add client to Client table, it's added automatically with signals to ClientsBalance. But the company field on ClientsBalance table is not updated to the current company (company=user.company), i would like that this field contain the current user company.

class Company(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=64)

class Client(models.Model):
company = models.ForeignKey('Company', on_delete=models.CASCADE)
name = models.CharField(max_length=256)

class ClientsBalance(models.Model):
company = models.ForeignKey('Company', on_delete=models.CASCADE)
client = models.OneToOneField('Client', on_delete=models.CASCADE,related_name='Client')

def create_client(sender, **kwargs):
    if kwargs['created']:
        client = ClientsBalance.objects.create(client=kwargs['instance'])
post_save.connect(create_client, sender=Client)

Solution

  • There is no relation between company of Client and company of ClientsBalance. You can update the value in signal like this.

     client = ClientsBalance.objects.create(client=kwargs['instance'], company=kwargs['instance'].company)