Django:CreateView中的transaction.atomic,form_valid() [英] Django: transaction.atomic in CreateView, form_valid()

查看:44
本文介绍了Django:CreateView中的transaction.atomic,form_valid()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 CreateView 中为 form_valid 提供 transaction.atomic 有意义吗?

Does it make sense to have transaction.atomic for form_valid in my CreateView?

    @transaction.atomic
    def form_valid(self, form):
        self.instance = form.save(commit=False)
        self.instance.event = self.request.event
        # When the super method is called the instance
        # is saved because it's a model form
        super().form_valid(form)
        return HttpResponseRedirect(self.get_success_url())

推荐答案

如果您的表单具有多对多字段,则事务装饰器将确保保存实例和多对多字段的查询在其中运行同一笔交易.

If your form has many-to-many fields, then the transaction decorator will ensure that the queries to save the instance and many-to-many fields run in the same transaction.

如果您的表单没有多对多字段,那么将只有一个SQL查询来保存行,并且不需要进行事务处理.

If your form doesn' have many-to-many fields, then there will be a single SQL query to save the row and a transaction isn't necessary.

顺便说一句,您的return语句正在复制 super().form_valid(form)会执行的操作.您可以执行 return super().form_valid(form),或者更明确地调用 save()可能更清晰.

As an aside, your return statement is duplicating what super().form_valid(form) would do. You could do return super().form_valid(form), or it might be clearer to call save() explicitly.

@transaction.atomic
def form_valid(self, form):
    self.instance = form.save(commit=False)
    self.instance.event = self.request.event
    self.instance.save()
    self.instance.save_m2m()  # if you have m2m fields
    return HttpResponseRedirect(self.get_success_url())

这篇关于Django:CreateView中的transaction.atomic,form_valid()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆