Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
jkarstens opened this issue Aug 25, 2020 · 2 comments

Comments

@jkarstens
Copy link
Contributor

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
@jkarstens
Copy link
Contributor Author

Oops, I see this has already been fixed by #138 just hasn't been released yet

@jheld
Copy link
Collaborator

jheld commented Aug 26, 2020

Please check the latest alpha release on PyPI (similar name also on the github releases page). I'm looking for a little more community feedback and then am happy to officially release. I think it's 1.3.0a5.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants