https://stackoverflow.com/questions/34264391/how-can-auto-create-uuid-column-with-django
new:
https://stackoverflow.com/questions/34264391/how-can-auto-create-uuid-column-with-django
import uuid
from django.db import models
class MyUUIDModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
existing: add new uuid column:https://stackoverflow.com/questions/61868694/django-model-add-uuid
problem is the new uuid column will result existing records get same uuid, cant be solved just by using migration
------------
it is trouble some because might have some impacts, its better to just do it when its cleanduring design, if you have to do it use:
https://stackoverflow.com/questions/35281003/django-migration-with-uuid-field-generates-duplicated-values# -*- coding: utf-8 -*
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
def create_uuid(apps, schema_editor):
Device = apps.get_model('device_app', 'Device')
for device in Device.objects.all():
device.uuid = uuid.uuid4()
device.save()
class Migration(migrations.Migration):
dependencies = [
('device_app', 'XXXX'),
]
operations = [
migrations.AddField(
model_name='device',
name='uuid',
field=models.UUIDField(blank=True, null=True),
),
migrations.RunPython(create_uuid),
migrations.AlterField(
model_name='device',
name='uuid',
field=models.UUIDField(unique=True)
)
]
!!! adding uuid as primary key replacing id will have performance issues
https://www.reddit.com/r/django/comments/keybyj/using_uuid_as_primary_key_bad_idea/The best answer to this question is going to come from researching the performance of a uuid primary key in the database than Django in general.
I was curious about this too, so I did some quick research on postgres and mysql. It seems that it's not ideal, but if you're doing it for security and privacy reasons, that benefit may outweigh the performance hit.
This was a pretty cool mysql article that benchmarks query performance based off table size and uuid type: https://blog.programster.org/mysql-performance-when-using-uuid-for-primary-key
No comments:
Post a Comment