如何在模型中直接使用全部大写的CharField? [英] How can I make all CharField in uppercase direct in model?

查看:91
本文介绍了如何在模型中直接使用全部大写的CharField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在所有Django模型的所有CharField中使用UpperCase.

I tried to use UpperCase in all my CharField, in all my Django Model.

今天,我的保存方法中有一些代码:

Today I have some code in my save method:

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吗?

But its take some time. There`s any method to put some uppercase=True in my models?

谢谢.

推荐答案

正确的方法是定义自定义模型字段:

The correct way would be to define custom model field:

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

您还需要解决南迁移问题 (如有必要),请添加以下代码:

you also need to resolve south migration issues (if necessary), by adding this code:

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

(最后一行中的路径取决于字段类的本地化.请阅读南方的文档以获取解释.)

(path in the last line depends on the field class localization. Please read the south docs for explanation.)

例如,当您使用shell创建模型对象并将其保存在变量中时,会有一个小的缺点:

Although there's a small downside when you use shell for instance to create model object and save it in variable:

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

您不会获得大写的值.您需要从数据库中检索对象.当我也找到如何解决此问题时,我将更新此帖子.

you won't get upper-cased value. You need to retrieve the object from the database. I will update this post, when I find out how to resolve this issue as well.

这篇关于如何在模型中直接使用全部大写的CharField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆