问题
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 ?
回答1:
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.
回答2:
The field is a UUID so you should pass a UUID to query it. It is quite straight-forward if you see it:
import uuid
id = uuid.UUID('193b6acc-2b78-4ddc-9ef8-632cde33ef74')
user_profile = User_Profile.objects.get(id=id)
回答3:
i assume your using postgreSQL :
The Django docs say : When used on PostgreSQL, this stores in a uuid datatype, otherwise in a char(32).
https://docs.djangoproject.com/fr/1.11/ref/models/fields/
来源:https://stackoverflow.com/questions/44109047/query-an-object-using-uuid-in-django