Opened 11 years ago
Closed 6 years ago
#24691 closed Cleanup/optimization (duplicate)
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 (2)
comment:1 by , 11 years ago
| Component: | Uncategorized → Documentation | 
|---|---|
| Summary: | UUIDField sets value before save → Document model._state.adding (since UUIDField sets value before save) | 
| Triage Stage: | Unreviewed → Accepted | 
| Type: | Bug → Cleanup/optimization | 
  Note:
 See   TracTickets
 for help on using tickets.
    
We should likely document
model._state.adding. See #24377 for a patch where we had to adapt the admin.