In Django, is there a way to create a object, create its related objects, then save them all at once?
For example, in the code below:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=255)
body = models.CharField(max_length=255)
class Tag(models.Model):
post = models.ForeignKey(Post)
title = models.CharField(max_length=255)
post = Post(title='My Title', body='My Body')
post.tag_set = [Tag(post=post, title='test tag'), Tag(post=post, title='second test tag')]
post.save()
I create a Post object. I then also want to create and associate my Tag objects. I want to avoid saving the Post then saving the Tags because if a post.save()
succeeds, then a tag.save()
fails, I'm left with a Post with no Tags.
Is there a way in Django to save these all at once or at least enforce better data integrity?