Django get_prep_value()中的自定义字段无效 [英] Custom field in Django get_prep_value() has no effect

查看:49
本文介绍了Django get_prep_value()中的自定义字段无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我做了一个类似于此答案的课程.看起来像:

So, I've made a similar class to this answer. It looks like:

class TruncatingCharField(models.CharField):
    description = _("String (truncated to %(max_length)s)")

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

我希望使用长度超过阈值的字符串来实例化具有此字段的模型会触发截断.但是,情况似乎并非如此:

I would expect that instantiating a model with this field with strings longer than the threshold should trigger truncation. However this appears not to be the case:

class NewTruncatedField(models.Model):
    trunc = TruncatingCharField(max_length=10)


class TestTruncation(TestCase):

    def test_accepted_length(self):
        trunc = 'a'*5
        obj = NewTruncatedField(trunc=trunc)
        self.assertEqual(len(obj.trunc), 5)

    def test_truncated_length(self):
        trunc = 'a'*15
        obj = NewTruncatedField(trunc=trunc)
        self.assertEqual(len(obj.trunc), 10)

第一个测试通过,如预期的那样,但是第二个失败,因为该字段未截断其值.肯定会调用 get_prep_value()方法(通过断点进行测试),并且返回点的 value 的输出会被正确截断.

The first test passes, as would be expected, but the second fails, as the field does not truncate its value. The get_prep_value() method is definitely being called (tested via breakpoints), and the output of value at the point of return is correctly truncated.

那为什么 obj 对象中的字段值不被截断?

Why then is the value of the field in the obj object not truncated?

推荐答案

我相信 get_prep_value()仅影响保存到数据库的内容,而不影响Python对象的内部值.

I believe get_prep_value() only effects what is saved to the DB, not the internal value of the Python object.

尝试覆盖 to_python() 并在其中移动逻辑.

Try overriding to_python() and moving your logic there.

这篇关于Django get_prep_value()中的自定义字段无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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