使用来自不同Model的字段值进行Django Clean_Field验证

时间:2017-03-25 18:59:39

标签: django django-forms

我正在尝试根据不同模型中另一个字段的值验证ModelForm中的表单字段。

这是我的ModelForm。 CompanyData Model包含一个" arr"我希望用作要验证的值的字段(" rev_goal"更高):

from django.forms import ModelForm
from django import forms
from django.core.exceptions import ValidationError

from company_data.models import CompanyData
from plans.models import Plan

class PlanCreateForm(forms.ModelForm):

    def clean_rev_goal(self):
        rev_goal = self.cleaned_data['rev_goal']
        company_data = self.object.companydata = CompanyData.objects.get # This is wrong. But how do I get the arr field from CompanyData here so the next line of code works?**
        if rev_goal < company_data.arr:
            raise ValidationError("Revenue goal must be greater than current ARR $")
        return rev_goal

    class Meta:
        model = Plan
        fields = ['plan_name', 'rev_goal', 'months_to_project', 'cpl', 'conv_rate']

要求提供更多详细信息,因此这两个模型显示了两者之间的关系:

class CompanyData(models.Model):
    user = models.OneToOneField(User)
    arr = models.DecimalField(max_digits=20, decimal_places=2, validators=[MinValueValidator(1)])
    num_cust = models.IntegerField(validators=[MinValueValidator(1)])

class Plan(models.Model):
    companydata = models.ForeignKey(CompanyData, related_name='companydata',
    on_delete=models.CASCADE)
    user = models.ForeignKey(User)


    plan_name = models.CharField(max_length=255)
    rev_goal = models.DecimalField(max_digits=20, decimal_places=2, validators=[validate_rev_goal])
    months_to_project = models.DecimalField(max_digits=20, decimal_places=0, validators=[MinValueValidator(1)])
    cpl = models.DecimalField(max_digits=20, decimal_places=2, validators=[MinValueValidator(.01)])
    conv_rate = models.DecimalField(max_digits=5, decimal_places=2, validators=[MinValueValidator(.01)])

我认为这完全错了?或者是否可以在ModelForm中访问不同模型的字段的值?在此先感谢您的帮助!

0 个答案:

没有答案