简体   繁体   中英

UNIQUE constraint failed in django project

I have an application in django 1.11, where I have an app 'accounts' to manage users. User can have assigned roles, with which there are problems when creating usera using manager.

When adding a username, I get an error:

IntegrityError at /accounts/add_user/

UNIQUE constraint failed: accounts_role.id

Here is my model:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('Email address'), unique=True)
    first_name = models.CharField(_('First name'), max_length=60, blank=True)
    last_name = models.CharField(_('Last name'), max_length=60, blank=True)
    roles = models.ManyToManyField(Role, unique=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    objects = UserManager()

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

Below is Role class:

class Role(models.Model):
    ADMIN = 1
    PLAYER = 2
    ROLE_CHOICES = (
        (ADMIN, 'admin'),
        (PLAYER, 'player'),
    )

    id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, default=2, primary_key=True, unique=False)

    def __str__(self):
        return self.get_id_display()

Here is manager:

class UserManager(BaseUserManager):
    def create_user(self, email, password):
        user = self.model(email=email, password=password)
        user.set_password(password)
        user.is_staff = False
        user.is_superuser = False
        user.save(using=self._db)
        role = Role.objects.create(id=2)
        user.roles.add(role)
        return user

In create_user , you should assign one or more existing roles to the new user rather than trying to create the same new role every time (with always the same primary key which obviously violates the unique constraint).

Your Role model defines only two roles. Create them separately from the user creation process and then assign them:

def create_user(self, email, password):
    # (...)   
    role = Role.objects.get(id=2)
    user.roles.add(role)

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