在检查另一个表单集的有效性之前保存模型(对于外键) [英] Saving model before checking validity of another formset (for foreign key)

查看:41
本文介绍了在检查另一个表单集的有效性之前保存模型(对于外键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在同一视图中将外键保存到模型中,您通常会看到:

For saving foreign keys to the model in the same view you often see:

if form1.is_valid():
    if form2.is_valid():
        form_obj = form.save()
        form2_obj = form2.save(commit=False)
        form2_obj.foreign_key = form_obj
        form2_obj.save()

但是对于在每个表单中循环的表单集,您要保存多次form1对象(这样做有什么作用吗?),并且可能存在某种形式的表单在循环中无效.

But for formsets where you loop through each form, you are saving the form1 object multiple times (does this do anything?) and there could be an a form that is not valid some way through the loop.

除非我丢失了某些东西,否则我想出的解决方案是先进行所有有效性检查,然后在确保所有内容都有效之后再次通过表单集(需要进行两次)或在确定有效后保存form1对象,但是如果遇到无效的formset,则将其删除.

Unless there is something i'm missing, the solutions i've come up with is to either do all the validity checking first, then go through the formset again once you make sure everything is valid (need to go through twice) or to save the form1 object after you make sure that is valid but delete it if you come across something in the formset that is invalid.

推荐答案

从@karthikr的评论中,我看到我要去哪里了.我原本以为您必须分别验证表单集中的每个表单,但是 formset.is_valid()涵盖了每个表单,只要您在所有表单集检查之后都保存了表单,就可以了.

From the comment by @karthikr i see where i was going wrong. I originally thought you had to validate each form in a formset individually, but formset.is_valid() covers each form so as long as you save the form after all formset checks then it should be okay.

if form1.is_valid():
    if formset.is_valid():
        form1_obj = form1.save()
        for form in formset:
            form_obj = form.save(commit=False)
            form_obj.foreign_key = form1_obj
            form_obj.save()

这篇关于在检查另一个表单集的有效性之前保存模型(对于外键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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