-
Notifications
You must be signed in to change notification settings - Fork 193
Closed
Description
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
Labels
No labels