Use name as a primary key instead of id in a User model Django

I am building a REST Api on Django RF and React on front end. I have users and I need the users to access their accounts via their nickname, not id (users/bob, users/john etc.). I have been thinking to change a default Django pk to be a username. So that when I make a request from React, I'll user the name. My User model is pretty straightforward:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=32, unique=True)
    name = models.CharField(primary_key=True, max_length=64, unique=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    def __str__(self):
        return self.email

But I have doubts if this is a good idea and whether I might get in some unexpected issues in the future. I have always used PK before. Is this a good practice to do it this way or should I still use IDs as a PK, show names on front end but make requests to users' IDs under the hood?

Upvotes: 0

Views: 1063

Answers (1)

vpdiongzon
vpdiongzon

Reputation: 679

Its best way if you leave the primary key as it is, you can just adjust the DRF lookup_field, instead of id, used the name.

e.g.:

Class UserViewset(viewsets.ModelViewSet):
   lookup_field = 'name' #default is id

Upvotes: 1

Related Questions