Django模型 - 准备数据库的数据

时间:2012-04-27 23:14:26

标签: django django-models

我有一张要求提供电话号码的表格。我需要确保只有数字[0-9]保存在数据库中。

在Django documentation 中它说:

保存时会发生什么?

3)准备数据库的数据。要求每个字段以可写入数据库的数据类型提供其当前值。

这是怎么发生的?或者更具体地说,我如何确保清洁它?我知道我可以覆盖模型保存方法,但似乎有更好的方法,我只是不知道该怎么做。

我想我可以为它写一个自定义字段,但这似乎有点过分了。

另外,我意识到我可以在表单上进行验证,但它真的感觉就像剥离了模型中的字符一样。

3 个答案:

答案 0 :(得分:2)

关于第3点的具体问题与django使用该术语的方式中的“清理”略有不同。

  

3)准备数据库的数据。要求每个字段以可写入数据库的数据类型提供其当前值。

第3点是关于将python对象值转换为适合数据库的值。具体而言,这是在Field.get_prep_valueField.get_db_prep_value

中完成的

https://docs.djangoproject.com/en/dev/howto/custom-model-fields/#django.db.models.Field.get_prep_value

它与to_python相反,它取一个DB值并将其转换为python对象。

至于确保只存储数字0-9,这将在Field s clean方法(子类IntegerField)中完成,形成clean方法,形式为{{1}方法或模型clean_FIELDNAME

答案 1 :(得分:1)

您可以为对象模型添加自定义表单清理方法 - 请查看本文https://docs.djangoproject.com/en/dev/ref/forms/validation/#form-field-default-cleaning

查看“清理特定字段属性”

答案 2 :(得分:0)

使用django model form + custom form field cleaning

以下是您可能正在寻找的内容的快速示例,其中MyModel是包含电话号码字段的模型,我在此处将其命名为tel

import re

class MyForm(ModelForm):
    class Meta:
        model = MyModel

    def clean_tel(self):
        tel = self.cleaned_data.get('tel', '')  # this is from user input

        # use regular expression to check if tel contains only digits; you might wanna enhance the regular expression to restrict the tel number to have certain number of digits.
        result = re.match(r'\d+', tel)  
        if result:
            return tel  # tel is clean so return it
        else:
            raise ValidationError("Phone number contains invalid character.")