query an object using uuid in django

Viewed 13103

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)

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')]

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'

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.

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

3 Answers
Related