Opened 2 years ago

Closed 2 years ago

#28299 closed New feature (duplicate)

Adding a unique UUIDField to an existing model immediately fails with a database constraint error

Reported by: Tom Forbes Owned by: nobody
Component: Migrations Version: master
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

If you want to add a unique UUIDField to an existing model, you would add the following field definition (as per the docs):

column = models.UUIDField(unique=True, default=uuid.uuid4)

However, upon creating and running a migration Django calls the default function *once*, then attempts to update all rows in a single query, which obviously violates the unique constraint and throws a database error.

This is particularly annoying and possibly confusing to new users (the error message is not exactly descriptive), and there does not seem to be an easy way of overriding it without creating your own custom RunPython migrations that sequentially calls the default function for each row.

Because it's pretty common to have a unique UUIDField, and because it's a problem you immediately run into when adding it to an existing model, could a workaround be added in the migrations framework to be a bit smarter about this? Or perhaps in a more generic sense, if unique=True then re-evaluate the default for each row rather than once during an UPDATE statement.

Change History (1)

comment:1 Changed 2 years ago by Tim Graham

Resolution: duplicate
Status: newclosed
Type: UncategorizedNew feature

Duplicate of #23932 where the decision was to document the solution. If you want to revisit the design decision, feel free to offer a proof of concept on the DevelopersMailingList.

Note: See TracTickets for help on using tickets.
Back to Top