2012-04-27 52 views
1

我有一個表單,用於提供電話號碼。我需要確保只有數字[0-9]被保存在數據庫中。Django Models - 爲數據庫準備數據

在Django的documentation它說:

時會發生什麼,你救誰?

3)準備數據庫的數據。要求每個字段以可寫入數據庫的數據類型提供其當前值。

這是怎麼發生的?或者更具體地說,我如何確保清潔?我知道我可以重寫模型保存方法,但似乎有更好的方法,我只是不知道該怎麼做。

我想我可以爲它寫一個自定義字段,但這似乎在這裏矯枉過正。

另外,我意識到我可以將驗證放在窗體上,但它真的感覺就像剝掉了模型上的字符。

回答

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小號clean方法(子類IntegerField),形式clean方法,形式clean_FIELDNAME方法或模型clean來完成。

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.")