【问题标题】:Custom Django user model with UUID as the id field以 UUID 作为 id 字段的自定义 Django 用户模型
【发布时间】:2017-10-21 17:54:31
【问题描述】:

我正在尝试扩展用户模型并添加一些字段,以下是我的方法:

Class UserProfile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    mobile_number = models.CharField(max_length=20)
    gender = models.CharField(max_length=2, choices=GENDER_CHOICES)
    location = models.ForeignKey(Location, blank=True, null=True)

class User_One(UserProfile):
    field_1 = models.CharField(max_length=20)
    ....
    ....

class User_Two(UserProfile):
    field_1 = models.CharField(max_length=20)
    ....
    ....

所以基本上有两种类型的用户 User_OneUser_Two 现在每当我们将这两种类型的用户保存到数据库中时,都会发生以下情况

  1. User 模型记录将使用值 1、2、3 等的单独 id 创建,
  2. User_One 模型记录将使用 id 的 1,2,3 创建
  3. User_Two 模型记录将使用 id 的 1,2,3 创建

因此,对于每个模型记录的保存,Django 或数据库都会生成 id 的 1、2、3。

但是我有一个要求,用户模型应该为 id 字段值生成一个uuid 来代替整数,这可能吗?

我的意思是像下面这样

class User_Profile(models.Model):
    id = models.IntegerField(default=uuid.uuid4)

【问题讨论】:

标签: python django django-models django-users


【解决方案1】:

使用 uuid 作为主键需要几个额外的步骤:

  1. 使用 UUIDField 代替 InegerField 作为您的 id 字段,因为 uuid 不完全是整数
  2. 为该字段指定primary_key=True

要获取自定义用户模型,请将其子类化为 django.contrib.auth.models.AbstractUser 并在您的设置中指定 AUTH_USER_MODEL

import uuid
from django.contrib.auth.models import AbstractUser
from django.db import models

class UserProfile(AbstractUser):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4)

然后在你的设置文件中:

AUTH_USER_MODEL = 'youruserapp.UserProfile'

在进行任何迁移(创建数据库)之前这样做很重要,否则这将不起作用。

【讨论】:

  • 我们可以生成这个uuid 来代替标准User 模型id 字段的id 值吗?
  • @shivakrishna 是的,绝对是。你需要一个custom user model
  • 我们需要为上述用户模型使用任何自定义 UserManager 吗?
  • 太棒了,所以现在我们可以继承User_Profile这个模型,并且可以创建任何数量的模型,比如User_one(User_Profile), User_two(User_Profile)等,
  • @shivakrishna 是的,它应该可以工作。我不知道你的确切要求,如果你想在数据库中保留一个表,你可能想使用proxy inheritance
猜你喜欢
  • 2021-04-15
  • 1970-01-01
  • 2020-09-09
  • 2011-04-08
  • 2017-03-31
  • 2021-12-08
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多