1

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
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
lionel
  • 140
  • 1
  • 2
  • 12

1 Answers1

2

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)
            )
        ]
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555