6
我有一個模型文件,它使用post_save
信號在另一個表中創建鏈接的行。以典型的方式,我可以從我的一個視圖創建一個頁面,用@ transaction.atomic進行裝飾。django信號是否也包含在transaction.atomic裝飾器中?
我想知道這個裝飾器是否會將Page對象和SharedPage對象的創建置於同一個事務中。從Django文檔中不清楚,信號是這個原子事務的一部分。
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')