简体   繁体   中英

django user model and custom primary key field

Django by default makes a primary key field on each model named " id ", with a type of AutoField . On my models, I'm overriding this to use a custom UUIDField as the primary key by using the " primary_key " attribute. I would also like the User model in django.contrib.auth to have a UUIDField as the primary key, but this doesn't seem to be possible without changing the User model source code.

Is there any recommended way to approach this problem?

With the release of Django 1.5, the authentication backend now supports custom user models:

https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model

An email field can be used as the username field and the primary_key argument can be set on it:

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=254, unique=True, db_index=True, primary_key=True)

    USERNAME_FIELD = 'email'

this doesn't seem to be possible without changing the User model source code.

Correct. Unless you are willing to change (or replace) User there isn't a way.

One (tenuous, hackish) way to do this would be to attach an UserProfile for each User instance. Each User should have exactly one UserProfile . You can then add your UUIDField to the profile. You will still have to do custom querying to translate from UUIDField to id .

If you don't like the name UserProfile you can rename it suitably. The key is that you have a one-to-one relationship to User .

One could leverage just the AbstractUser and make the following changes

class CustomUser(AbstractUser):
    email = models.EmailField(max_length=254, unique=True, db_index=True, primary_key=True)
    name = models.CharField(max_length=50)

    USERNAME_FIELD = 'email'
    REQUIRED_FILEDS = ['name']

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