python - 获取 django 模型字符串字段作为 str 而不是 unicode

标签 python django string unicode

django 将 CharField 字段获取为 unicode,而有时需要 str。编写循环字段、检查类型以及如果是 unicode 则将其转换为 str 的代码既低效又乏味。

是否已有可以处理该问题的功能?
如果不是,处理这个问题最优雅的方法是什么?

最佳答案

您可以对 models.CharField 类进行子类化并重写 to_python 方法:

from django.utils.encoding import smart_str
from django.db.models import CharField

class ByteStringField(CharField):
    def to_python(self, value):
        if isinstance(value, str) or value is None:
            return value
        return smart_str(value)

smart_str 相当于 CharFields 中通常使用的 smart_unicode 函数的字节串。

编辑:正如乔纳森所说,如果您使用的是 South,请记住 extend south's introspection rules

关于python - 获取 django 模型字符串字段作为 str 而不是 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17866917/

相关文章:

python - 错误 "The parameter redirect_uri is required"

javascript - 后效果 : Add prefix to result of an effect

python - 关闭科学记数法和全局偏移

python - 在 python 工具套件中延迟导入

javascript - 在外部 javascript 文件/django 中使用 DOM 时出现问题

c - 从 C 源代码中删除字符串

C# - 如何格式化日期时间以删除尾随零

python - 如何计算二进制字符串中的结尾 0

python - 在字典中连接键和值

来自另一个类的元类上的 Python super