在 Django CharFields 中以 max_length 自动截断字段 [英] Auto-truncating fields at max_length in Django CharFields
问题描述
我有一个设置了 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.
推荐答案
您可以创建一个自动截断字段的自定义字段(我认为此代码应该可以工作,但请仔细检查):
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.py
文件中使用 models.CharField
,而只需使用 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屋!