Home > Net >  Django username only unique for active user
Django username only unique for active user

Time:09-15

I've created a custom model User with the field username (char field) and active (boolean field). The username field should only be unique when the user is active, otherwise, I want to rename the user to 'inactive' so the username can be reused by a different user. How can this be done? I tried this, but it throws an error:

class User(models.Model):
  username = models.CharField(max_length=30, unique=isActive())
  active = models.BooleanField(default=True)

  def isActive(self):
    return self.active

CodePudding user response:

You can work with a UniqueConstraint [Django-doc] with a condition=…:

from django.db.models import Q


class User(models.Model):
    username = models.CharField(max_length=30)
    active = models.BooleanField(default=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=('username',), condition=Q(active=True)
            )
        ]
  • Related