Shi*_*dla 7 python django uuid django-queryset
我正在使用 uuid 创建一个 id 字段,它是主键,如下所示
import uuid
class User_Profile(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
Run Code Online (Sandbox Code Playgroud)
因此,每当我们将对象保存到数据库中时,它都会保存为 UUID 实例而不是字符串,如下所示
user_profiles = User_Profile.objects.values_list('id', flat=True)
print user_profiles
[UUID('193b6acc-2b78-4ddc-9ef8-632cde33ef74')]
Run Code Online (Sandbox Code Playgroud)
现在如何使用 django ORM 查询它?因为它没有保存为字符串,所以我无法按如下方式获取它并出现错误
user_profile = User_Profile.objects.get(id='193b6acc-2b78-4ddc-9ef8-632cde33ef74')
Run Code Online (Sandbox Code Playgroud)
ValueError: invalid literal for int() with base 10: '193b6acc-2b78-4ddc-9ef8-632cde33ef74'
Run Code Online (Sandbox Code Playgroud)
当我从 Django 中的查询参数收到这个 uuid 作为字符串时,我也尝试将它从字符串转换为 uuid,如下所示,我得到了错误
import uuid
id = uuid.UUID('193b6acc-2b78-4ddc-9ef8-632cde33ef74')
user_profile = User_Profile.objects.get(id=id)
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
那么最后如何从 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>
Run Code Online (Sandbox Code Playgroud)
如果问题仍然存在,请尝试删除数据库和迁移并重新创建。您遇到的问题与数据库无关,可能是您的配置中的问题。
该字段是一个 UUID,因此您应该传递一个 UUID 来查询它。如果你看到它,那就很简单了:
import uuid
id = uuid.UUID('193b6acc-2b78-4ddc-9ef8-632cde33ef74')
user_profile = User_Profile.objects.get(id=id)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9480 次 |
| 最近记录: |