我正在使用 uuid 创建一个 id 字段,该字段是主键,如下所示
import uuid
class User_Profile(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
因此,每当我们将对象保存到数据库中时,它都会保存为 UUID 实例,而不是如下所示的字符串
user_profiles = User_Profile.objects.values_list('id', flat=True)
print user_profiles
[UUID('193b6acc-2b78-4ddc-9ef8-632cde33ef74')]
现在如何使用 django ORM 查询它?因为它没有保存为字符串,所以我无法按如下方式获取它并收到错误
user_profile = User_Profile.objects.get(id='193b6acc-2b78-4ddc-9ef8-632cde33ef74')
error:
ValueError: invalid literal for int() with base 10: '193b6acc-2b78-4ddc-9ef8-632cde33ef74'
当我从 Django 中的查询参数中收到此 uuid 作为字符串时,我还尝试将其从字符串转换为 uuid,如下所示,但出现错误
import uuid
id = uuid.UUID('193b6acc-2b78-4ddc-9ef8-632cde33ef74')
user_profile = User_Profile.objects.get(id=id)
error:
ProgrammingError: operator does not exist: uuid = numeric
LINE 1: ...ifications" FROM "tc_user_profile" WHERE "tc_user_profile"."id" = 33539211...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
那么最后如何从 django 数据库查询 uuid id 字段?