在Django CharFields中以max_length自动截断字段 [英] Auto-truncating fields at max_length in Django CharFields

查看:427
本文介绍了在Django CharFields中以max_length自动截断字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 max_length 集合的字段。当我保存模型实例时,字段的值大于 max_length ,Django在数据库级别强制执行 max_length 。 (有关模型,请参阅Django文档: http ://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.CharField.max_length

I have a field that has a max_length set. When I save a model instance, and the field's value is greater than max_length, Django enforces that max_length at the database level. (See Django docs on models: http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.CharField.max_length)

然而因为我使用Postgres,所以我收到一个 DatabaseError 这样的异常:

However, since I am using Postgres, I receive a DatabaseError exception like this:

DatabaseError: value too long for type character varying(1000)

截断值(所以我没有异常)。现在,我可以手动执行,但我真正想要的是让我的所有模型自动截断值。 (不一定是智能的,只需在第999个字符处切掉它就可以了。)

I would prefer to instead auto-truncate the value (so I don't have an exception). Now, I can do this manually, but what I would really want is to have all of my models auto-truncate the value. (Not necessarily intelligently. Just cutting it off at the 999th character is fine.)

我应该写一个从models.Model导入的自定义类,并覆盖save )方法,循环遍历每个_meta.field,检查max_length,然后截断?

Should I just write a custom class that imports from models.Model and override the save() method, looping through each _meta.field, checking for the max_length, and then truncating? That seems inelegant and there must be a better way.

推荐答案

您可以创建自动截断字段的自定义字段(I认为这个代码应该工作,但是仔细检查一下):

You could create a custom field that auto-truncates the field (I think this code should work, but double-check it):

class TruncatingCharField(models.CharField):
    def get_prep_value(self, value):
        value = super(TruncatingCharField,self).get_prep_value(value)
        if value:
            return value[:self.max_length]
        return value

然后,而不是使用 models.CharField 您的 models.py 文件,您只需使用TruncatingCharField。

Then, instead of using models.CharField in your models.py file, you'd just use TruncatingCharField instead.

get_prep_value 准备值对于要在数据库中插入的字段,因此它是截断的理想位置。

get_prep_value prepares the value for a field for insertion in the database, so it's the ideal place to truncate.

这篇关于在Django CharFields中以max_length自动截断字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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