如何拥有没有破折号的models.UUIDField字段

Che*_*eng 7 python django

我试图models.UUIDField通过使用default=uuid.uuid4().hex(而不是default=uuid.uuid4())

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    api_key = models.UUIDField(default=uuid.uuid4().hex, editable=False, unique=True)
    subscription = models.IntegerField(
        choices=[(s.value, s.name) for s in Subscription],
        null=False,
        blank=False
    )

    def __str__(self):
        return str(self.api_key)
Run Code Online (Sandbox Code Playgroud)

但是,结果仍然带有破折号。

django=# select * from users_profile;
 id |               api_key                | secret_key | subscription | user_id
----+--------------------------------------+------------+--------------+---------
  1 | 9da3546c-660c-46c6-adc4-6a13e6ee202b |            |            0 |       1
  2 | 9cbc3a68-7f50-4b18-9e61-7b009f22a0e8 |            |            0 |       2
(2 rows)
Run Code Online (Sandbox Code Playgroud)

我可以知道如何在没有破折号的情况下使用 models.UUIDField 字段吗?. 我想在没有破折号的情况下存储在数据库中,并在没有破折号的情况下使用它。

小智 7

你有机会使用 PostgreSQL 吗?的UUIDField可以是使用天然uuid类型的列。它仅使用 16 个字节(没有破折号)有效地存储它。如果是这种情况,它不会存储破折号,仅在您select.

好消息是,在 Python 代码中,您将获得一个UUIDobject,因此您可以self.api_key.hex获取一个没有破折号的字符串。


JPG*_*JPG 5

使用CharFieldfield 而不是UUIDField,

def generate_uuid():
    return uuid.uuid4().hex


class Profile(models.Model):
    api_key = models.CharField(default=generate_uuid, editable=False, unique=True, max_length=40)
Run Code Online (Sandbox Code Playgroud)

  • @JPG 对于大多数数据库来说,uuid 字段的性能将明显优于 charfield。 (2认同)