简体   繁体   中英

Create a model object when creating a user in Django, UNIQUE constraint failed

I have this model:

class Family(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=255, unique=False)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['name']

And I am also using this function to create a family object when a user is created:

@receiver(models.signals.post_save, sender=User)
def user_created(sender, instance, created, **kwargs):
    if created:
        Family.objects.create(user=instance)

I have a couple questions:

  1. I am getting an django.db.utils.IntegrityError: UNIQUE constraint failed: family_tree_family.name error, how to resolve it?
  2. How to use the **kwargs in user_created function. I create users using curl .

First, thanks to everyone who helped out.

I managed to figure the problem, and it was that the field name in family model must also be unique. Even if unique=False attribute was used. Therefore, the answer is to automatically create a unique name that does not exist before. Hence, I used instance.username since this value must always be unique:

@receiver(models.signals.post_save, sender=User)
def user_created(sender, instance, created, **kwargs):
    if created:
        Family.objects.create(user=instance, name=instance.username)

I would like to have a better alternative other than instance.username . Maybe if I could use **kwargs somehow.

In user_created try adding instance.family.save() after Family.objects.create(user=instance)

@receiver(models.signals.post_save, sender=User)
def user_created(sender, instance, created, **kwargs):
    if created:
        Family.objects.create(user=instance)
    instance.family.save()

and try changing user field in family class if that does not work.

user = models.OneToOneField(User, on_delete=models.CASCADE)

Hopefully that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM