在Django中使用uuid查询对象 [英] query an object using uuid in django

查看:426
本文介绍了在Django中使用uuid查询对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用uuid创建一个ID字段,它是如下所示的主键

I am using uuid for creating an id field which is primary key as below

import uuid

class User_Profile(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

因此,每当我们将对象保存到数据库中时,它都将另存为UUID实例而不是下面的字符串

So whenever we save an object into the database it was saving as an UUID instance instead of string as below

user_profiles = User_Profile.objects.values_list('id', flat=True)
print user_profiles
[UUID('193b6acc-2b78-4ddc-9ef8-632cde33ef74')]

现在如何使用django ORM查询它?因为它没有保存为字符串,所以我无法按以下方式获取它并收到错误

now how to query it by using django ORM ? since it was not saving as a string i can't able to fetch it as below and getting an error

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作为字符串时,我也尝试通过将其从string转换为uuid来实现下面,我得到了一个错误

when i recieved this uuid as string from query params in Django, i also tried by converting it in to uuid from string as below and i got the error

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字段?

So finally how to query a uuid id field from django database ?

推荐答案

实际上,我已经在计算机上使用数据库PostGres进行了尝试,并且可以正常工作,

Actually, I have tried this in my machine with database PostGres and it works,

>>> 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>

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

If the problem still persists, try deleting the database and migrations and recreate it. The problem you are facing is not related to the database, it maybe something in your configuration.

这篇关于在Django中使用uuid查询对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆