Custom field in Django get_prep_value() has no effect

和自甴很熟 提交于 2021-02-10 11:46:37

问题


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)

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.

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


回答1:


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

Try overriding to_python() and moving your logic there.



来源:https://stackoverflow.com/questions/31093407/custom-field-in-django-get-prep-value-has-no-effect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!