Django:如何覆盖 form.save()? [英] Django: How to override form.save()?

查看:24
本文介绍了Django:如何覆盖 form.save()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型有很多布尔字段.我将它们分成 3 组,我将它们渲染为 MultipleChoiceField 和修改后的 CheckboxSelectMultiple.

My model has quite a few boolean fields. I've broken these up into 3 sets which I'm rendering as a MultipleChoiceField w/ a modified CheckboxSelectMultiple.

现在我需要将这些数据保存回数据库.即,我需要将单个小部件返回的数据拆分为多个布尔列.我认为这适用于 save() 方法,不是吗?

Now I need to save this data back to the DB. i.e., I need to split the data returned by a single widget into multiple boolean columns. I think this is appropriate for the save() method, no?

问题是,我该怎么做?像这样吗?

Question is, how do I do I do it? Something like this?

def save(self, commit=True):
    # code here
    return super(MyForm, self).save(commit)

如果是这样... 我该如何设置这些值?

self.fields['my_field'].value = 'my_flag' in self.cleaned_data['multi_choice']

或者什么?所有数据都存储在哪里?

推荐答案

你想要存储数据的地方是你的新模型实例:

The place you want your data to be stored is your new model instance:

def save(self, commit=True):
    instance = super(MyForm, self).save(commit=False)
    instance.flag1 = 'flag1' in self.cleaned_data['multi_choice'] # etc
    if commit:
        instance.save()
    return instance

这篇关于Django:如何覆盖 form.save()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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