Reputation: 121
Django noob here
I have created a model using
customer_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
After migrating the model to MySQL, I tried to add data into mysql using
insert into customer_customer (customer_id, ...) values (uuid(), ...)
The data gets inserted properly in MySQL with a unique code, however, when I try to display this via Django admin tool (this table feeds into a property for users), it throws a badly formatted uuid error.
File "/usr/lib/python2.7/uuid.py", line 134, in __init__
raise ValueError('badly formed hexadecimal UUID string')
ValueError: badly formed hexadecimal UUID string
Please discuss if there is another way of creating seed data directly in MySQL.
Upvotes: 1
Views: 3192
Reputation: 39
Documentation states that if you use a MySQL database, Django will store a string (char32):
UUIDField. A field for storing universally unique identifiers. Uses Python’s UUID class. When used on PostgreSQL, this stores in a uuid datatype, otherwise in a char(32).
Python's uuid module gives you the following options to generate UUIDs:
>>> import uuid
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'
In your case (using uuid4 as default in the Django module), you will need to use the "UUID.uuid4().hex" option in order to save the UUID as a string, just like Django would save it in your MySql database.
Upvotes: 0
Reputation: 1404
Try this:
insert into customer_customer (customer_id, ...) values (Replace(uuid(),'-',''), ...)
then it will work.
Upvotes: 0
Reputation: 3658
A field for storing universally unique identifiers. Uses Python’s UUID class. When used on PostgreSQL, this stores in a uuid datatype, otherwise in a char(32).
So with MySQL django handles the uuid, and manages the field as Char32. You can't use native MySQL uuid.
If you have to create uuid from the MySQL side, use a CharField in django model, and populate it:
class MyModel(models.Model):
fld = models.CharField(max_length=36)
Then when saving:
import uuid
MyModel.fld = str(uuid.uuid4())
As a default:
fld = models.CharField(max_length=36, default=uuid.uuid4)
Upvotes: 1