Skip to content

created or updated check in pre_save doesn't consider models with a pre-assigned pk #161

@jkarstens

Description

@jkarstens

Models with a OneToOneField(primary_key=True) inherit their parent instance's pk (even before the child instance is saved).

For example, with the following setup:

class Profile(models.Model):
    user = models.OneToOneField(User, models.CASCADE, primary_key=True)
    
    @receiver(post_save, sender=User)
    def create_or_update_profile(sender, **kwargs):
        if kwargs['created']:
            profile = Profile.objects.create(user=kwargs['instance'])
        else:
            kwargs['instance'].profile.save()

pre_save throws an exception on every creation of a Profile object because pre_save assumes the presence of a pk on a model instance implies that the instance has been created

            if instance.pk is None:
                created = True
            else:
                created = False

but then the exception is thrown with an attempt to retrieve the instance that doesn't exist yet

            if not created:
                old_model = sender.objects.get(pk=instance.pk)

Perhaps the created or updated check should be changed to something like this?

            try:
                sender.objects.get(pk=instance.pk)
            except sender.DoesNotExist:
                created = True
            else:
                created = False

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions