【发布时间】:2017-10-21 21:15:48
【问题描述】:
我正在使用 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')
错误:
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)
错误:
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 字段?
【问题讨论】:
标签: python django django-queryset uuid