首页 > 解决方案 > 如何让 models.UUIDField 字段没有破折号

问题描述

我试图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)

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

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)

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

标签: pythondjango

解决方案


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

好消息是,在 Python 代码中你得到一个UUIDobject,所以你可以self.api_key.hex得到一个没有破折号的字符串。


推荐阅读