Opened 4 years ago

Last modified 4 years ago

#24691 new Cleanup/optimization

Document model._state.adding (since UUIDField sets value before save)

Reported by: Mattia Procopio Owned by: nobody
Component: Documentation Version: 1.8
Severity: Normal Keywords: uuid UUIDField
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When using a pk I expect the behaviour we had in the past meaning that inside .save() method checking for self.pk gives me a clue of creation vs update (documentation confirms that https://docs.djangoproject.com/en/1.8/ref/models/instances/#how-django-knows-to-update-vs-insert). This is not working when using UUIDField since when we enter the save method the pk is already set to the default value.

to reproduce

import uuid

from django.db import models

class AwesomeModel(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True)
    x = models.CharField(max_length=10)

    def save(self, *args, **kwargs):
        if self.pk:
            print("we have already a pk set")
        return super(AwesomeModel, self).save(*args, **kwargs)


a = AwesomeModel(x='some')
a.save()
we have already a pk set

Change History (1)

comment:1 Changed 4 years ago by Tim Graham

Component: UncategorizedDocumentation
Summary: UUIDField sets value before saveDocument model._state.adding (since UUIDField sets value before save)
Triage Stage: UnreviewedAccepted
Type: BugCleanup/optimization

We should likely document model._state.adding. See #24377 for a patch where we had to adapt the admin.

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