如何检查django模型中的字段?

时间:2015-01-26 14:06:32

标签: python django model

我有这样的模特。我想检查团队的名称是否为“俄罗斯”,然后你需要指定团队的名称。

我想检查用户何时将数据输入表单。

我该怎么检查?

RUSSIA = 'RUS'
USA = 'USA'
GERMANY = 'GER'


COUNTRY = (
    (RUSSIA, "Russia"),
    (USA, "USA"),
    (GERMANY, "Germany"),
)


class Country(models.Model):

    country = models.CharField(max_length=3, choices=COUNTRY, default=RUSSIA)
    name_of_team = models.CharField(max_length=255, blank=True, null=True)

    def __unicode__(self):
        return self.name_of_team

1 个答案:

答案 0 :(得分:0)

您只需对clean模型ModelForm使用Country方法:

from django import forms
from .models import Country, RUSSIA


class CountryForm(forms.ModelForm):

    class Meta:
        model = Country

    def clean(self):
        cleaned_data = self.cleaned_data

        country = cleaned_data.get('country')
        name_of_team = cleaned_data.get('name_of_team')

        if country == RUSSIA and not name_of_team:
            self.add_error('name_of_team', 'You must supply a team name')

        return cleaned_data

有关表单验证的详细信息,请参阅https://docs.djangoproject.com/en/1.7/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

为了清晰起见,我还建议在Country模型中移动选择常量:

class Country(models.Model):

    RUSSIA = 'RUS'
    USA = 'USA'
    GERMANY = 'GER'


    COUNTRY_CHOICES = (
        (RUSSIA, "Russia"),
        (USA, "USA"),
        (GERMANY, "Germany"),
    )

    country = models.CharField(max_length=3, choices=COUNTRY_CHOICES,
        default=self.RUSSIA)

然后在你的表格中你可以做到:

. . .

def clean(self):
    . . .

     if country == Country.RUSSIA and not name_of_team:
        self.add_error('name_of_team', 'You must supply a team name')

    return cleaned_data

这在很大程度上取决于个人偏好,但我认为它提供了更好的可读性。