如何从不同的ModelForm字段中使用一些计算来填充模型字段值?

3
我希望在我的ModelForm中添加一个名为age的字段,并将它用来填充模型中的birth_year字段。
有什么惯用方式可以实现这个需求?我应该在我的表单、模型或元类中提供哪些方法呢?

这取决于您是否想在保存/更新模型实例时填充birth_year字段,或者您是否希望它成为一种动态解决方案,不需要保存即可根据age更新birth_year - WTK
1个回答

3
from datetime import datetime
import forms
from myapp.models import MyModel


class MyAgeForm(forms.ModelForm):
    age = forms.IntegerField()
    # define other custom fields here

    class Meta:
       model = MyModel
       # probably define what fields from the model to include/exclude here


    def save(self, *args, **kwargs):
        self.instance.birth_year = datetime.now().year - self.cleaned_data['age']
        return super(MyAgeForm, self).save(*args, **kwargs)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接