I have a model file that uses a post_save
signal to create a linked row in another table. In typical fashion, I can create a page from one of my views which is decorated with @transaction.atomic.
I would like to know if this decorator will put the creation of the Page object and the SharedPage object in the same transaction. It is not clear from the django docs that signals are a part of this atomic transaction.
models.py
class Page(models.Model):
name = models.CharField(default='My default page',max_length=200,blank=False)
created_at = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
slug = models.SlugField()
uuid = models.UUIDField(default=uuid.uuid4, editable=False)
is_public = models.BooleanField(default=False)
def __str__(self): # __unicode__ on Python 2
return self.name
class Meta:
ordering = ['position','created_at']
@receiver(post_save, sender=Page)
def create_shared_page_entry(sender, instance, created, **kwargs):
if created:
shared_page = SharedPage.objects.create(
page=instance,
user=instance.user,
can_edit=True
)
view.py
@require_http_methods(["POST"])
@transaction.atomic
def page_create(request):
name = request.POST.get('name')
page = Page.objects.create(name=name, owner=request.user)
data = serializers.serialize("json", [page])
return HttpResponse(data, content_type='application/json')