Home > Net >  Tips to better manage the creation of a non-nullable object through signals
Tips to better manage the creation of a non-nullable object through signals

Time:07-19

I find myself in this situation:

In models:

class Client(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # other...

signals.py:

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Client.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
        instance.client.save()

There are specific fields of the Client class that cannot be null and therefore I get errors like:

NOT NULL constraint failed: accounts_client.dob

What is the best solution in this case?

CodePudding user response:

The obvious answer is to just make sure that data is being passed to those fields to ensure the non-null constraint doesn't fail. As to how you do that, the easiest way is to set a default value on your field - this default doesn't necessarily need to be a fixed value, it can accept a callable function - however, it will not have the context of the object you are creating. To do that, you would need to override the save() method.

  • Related