2013-10-21 51 views
2

我試圖在我所有的CharField中,在我所有的Django模型中使用UpperCase。如何讓所有CharField在模型中直接使用大寫字母?

今天我有一些代碼在我保存方法:

def save(self, *args, **kwargs): 
     for field_name in ['razao_social', 'nome_fantasia', 'cidade', 'endereco','bairro', 'uf', 'cli_parc_nomeparc', 'cli_repr_nomerepr']: 
      val = getattr(self, field_name, False) 
      if val: 
       setattr(self, field_name, val.upper()) 
     super(Pessoa, self).save(*args, **kwargs) 

但它需要一些時間。有什麼方法可以在我的模型中放置一些大寫=真?

謝謝。

回答

4

正確的方法是定義自定義模型領域:

from django.db import models 
from django.utils.six import with_metaclass 


class UpperCharField(with_metaclass(models.SubfieldBase, models.CharField)): 
    def __init__(self, *args, **kwargs): 
     self.is_uppercase = kwargs.pop('uppercase', False) 
     super(UpperCharField, self).__init__(*args, **kwargs) 

    def get_prep_value(self, value): 
     value = super(UpperCharField, self).get_prep_value(value) 
     if self.is_uppercase: 
      return value.upper() 

     return value 

,並使用它,像這樣:

class MyModel(models.Model): 
    razao_social = UpperCharField(max_length=50, uppercase=True) 
    # next field will not be upper-cased by default (it's the same as CharField) 
    nome_fantasia = UpperCharField(max_length=50) 
    # etc.. 

還需要解決south migration issues(如有必要),通過將此代碼:

from south.modelsinspector import add_introspection_rules 
add_introspection_rules([ 
    (
     [UpperCharField], 
     [], 
     { 
      "uppercase": ["uppercase", {"default": False}], 
     }, 
    ), 
], ["^myapp\.models\.UpperCharField"]) 

(最後一行的路徑取決於字段類本地化。P租賃閱讀說明南方文檔)

雖然有一個小缺點,當你使用shell的實例來創建模型對象並將其保存在變量:

my_object = MyModel.objects.create(razao_social='blah') 
print my_object.razao_social 

你不會得到大寫的價值。您需要從數據庫中檢索對象。當我找到如何解決這個問題時,我會更新這篇文章。

+0

偉大的回答,有用的鏈接和+1南方信息。儘管你的代碼有一個小問題:由於你使用屬性名稱「is_uppercase」,南內省規則需要使用它。將中間行改爲:'「uppercase」:[「is_uppercase」,{「default」:False}],'' – Patrick

0

這裏是我的,而不必應付遷移骯髒和簡單的解決方案:

char_fields = [f.name for f in self._meta.fields if isinstance(f, models.CharField) and not getattr(f, 'choices')] 
    for f in char_fields: 
     val = getattr(self, f, False) 
     if val: 
      setattr(self, f, val.upper()) 
    super(Cliente, self).save(*args, **kwargs) 
5

下面是如何重寫一個Django模場,並使其大寫作爲Django 1.8

這將:

  • 由大寫的值保存到數據庫
  • 工作返回保存響應一個大寫的值。

下面的代碼:

from django.db import models 

class UpperCaseCharField(models.CharField): 

    def __init__(self, *args, **kwargs): 
     super(UpperCaseCharField, self).__init__(*args, **kwargs) 

    def pre_save(self, model_instance, add): 
     value = getattr(model_instance, self.attname, None) 
     if value: 
      value = value.upper() 
      setattr(model_instance, self.attname, value) 
      return value 
     else: 
      return super(UpperCaseCharField, self).pre_save(model_instance, add) 

如果你想這樣做,在Django的REST框架,下面的代碼:

from rest_framework import serializers 

class UpperCaseSerializerField(serializers.CharField): 

    def __init__(self, *args, **kwargs): 
     super(UpperCaseSerializerField, self).__init__(*args, **kwargs) 

    def to_representation(self, value): 
     value = super(UpperCaseSerializerField, self).to_representation(value) 
     if value: 
      return value.upper() 
相關問題