You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
The text was updated successfully, but these errors were encountered:
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.
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:
pre_save
throws an exception on every creation of a Profile object becausepre_save
assumes the presence of a pk on a model instance implies that the instance has been createdbut then the exception is thrown with an attempt to retrieve the instance that doesn't exist yet
Perhaps the created or updated check should be changed to something like this?
The text was updated successfully, but these errors were encountered: