Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

TransactionManagementError when saving model with OneToOne relationship in Django

I'm trying to make it so that when a User model is created, it also creates the corresponding MyAppProfile class to go with it. But when I do so, as I've seen online, I get an error.

An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.

I've tried various methods to do this, and they give that error when I try it. I can't figure out why I'm getting that error, or where exactly it's coming from.

My profile class:

class MyAppProfile(models.Model):
    user = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="myapp_profile")

    # Other fields for this app's profile go here

    def __str__(self):
        return f'{self.id}: MyApp Profile for {self.user.username}'

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)


@receiver(post_save, sender=AUTH_USER_MODEL)
def update_profile_signal(sender, instance, created, **kwargs):
    if created:
        MyAppProfile.objects.create(user=instance)
    instance.myapp_profile.save()

Edit:

My user model:

class User(AbstractUser):
    id = UUIDField()

    def save(self, *args, **kwargs):
        if not self.pk:
            saved = False
            attempts = 0
            while not saved:
                try:
                    if attempts > 5:
                        raise RuntimeError('Max attempts reached trying to save to database.')
                    super().save(*args, **kwargs)
                except IntegrityError:
                    attempts += 1
                    self.id = gen_uuid(length=8)
question from:https://stackoverflow.com/questions/65868724/transactionmanagementerror-when-saving-model-with-onetoone-relationship-in-djang

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You didn't show enough code here, but your code probably is running inside a transaction. Something like:

with transaction.atomic():
    profile.save()

When the transaction fails with an IntegrityError, you can't execute anything else inside this transaction, it is already terminated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...