gpt4 book ai didi

python - 在 Django 中使用 uuid 查询对象

转载 作者:行者123 更新时间:2023-12-03 14:39:45 24 4
gpt4 key购买 nike

我正在使用 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 字段?

最佳答案

实际上,我已经在我的机器上用数据库 PostGres 尝试过这个,它可以工作,

>>> user = User_Profile.objects.create()
>>> user
<User_Profile: User_Profile object>
>>> user.id
UUID('d92c2280-4682-42ea-86c3-a1ed993c0638')
#copied the string of uuid only.
>>> id = 'd92c2280-4682-42ea-86c3-a1ed993c0638'
>>> User_Profile.objects.get(id=id)
<User_Profile: User_Profile object>

>>> import uuid
#converted the string into UUID format
>>> id = uuid.UUID(id)
>>> id
UUID('d92c2280-4682-42ea-86c3-a1ed993c0638')
>>> User_Profile.objects.get(id=id)
<User_Profile: User_Profile object>

如果问题仍然存在,请尝试删除数据库和迁移并重新创建它。您面临的问题与数据库无关,可能与您的配置有关。

关于python - 在 Django 中使用 uuid 查询对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44109047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com