我尝试在所有的CharField中使用UpperCase,在我的所有Django模型中。
今天我的保存方法中有一些代码:
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)
但是需要一些时间。有什么方法可以在我的模型中加上一些大写= True?
感谢。
答案 0 :(得分:11)
以下是如何覆盖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 framework 中执行此操作,请输入以下代码:
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()
答案 1 :(得分:8)
正确的方法是定义自定义模型字段:
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"])
(最后一行中的路径取决于字段类本地化。请阅读南方文档以获取解释。)
虽然使用shell创建模型对象并将其保存在变量中时存在一个小缺点:
my_object = MyModel.objects.create(razao_social='blah')
print my_object.razao_social
你不会得到上限值。您需要从数据库中检索对象。当我发现如何解决这个问题时,我会更新这篇文章。
答案 2 :(得分: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)
答案 3 :(得分:0)
除了定义自定义字段,您还可以使用RegexValidator
:
from django.core.validators import RegexValidator
...
my_field = models.CharField(
max_length=255,
validators=[RegexValidator('^[A-Z_]*$',
'Only uppercase letters and underscores allowed.')],
)
(请参阅Docs)