[Fixed]-Saving objects and their related objects at the same time in Django

14👍

transactions to the rescue !

from django.db import transaction

with transaction.atomic():
   post = Post.objects.create('My Title', 'My Body')
   post.tag_set = [Tag(post, 'test tag'), Tag(post, 'second test tag')]

As a side note: I think you really want a many to many relationship between Post and Tag

4👍

override save…

class Post(models.Model):

    ...

    def save(self, *args, **kwargs):
        super(Post, self).save(*args, **kwargs)
        for tag in self.tag_set:
            tag.save()

This way you don’t have to write the transaction thing over and over again. If you want to use transactions, just implement it in the save method instead of doing the loop.

Leave a comment