我写了一个自定义django字段来规范化我们系统收到的URL。但是,该网址只会在重新加载后返回归一化的值。
from django.db import models
def _rewrite_internal_url(url):
#
return 'http://www.google.com/1.jpg'
class NormalizedURLField(models.URLField):
def to_python(self, value):
value = super().to_python(value)
return _rewrite_internal_url(value)
def from_db_value(self, value, expression, connection):
if value is None:
return value
return _rewrite_internal_url(value)
class DjangoTest(models.Model):
url = NormalizedURLField()
instance = DjangoTest.objects.create(url="http://www.google.com/2.jpg")
print(instance.url) # still http://www.google.com/2.jpg
instance.referesh_from_db()
print(instance.url) # update to http://www.google.com/1.jpg
答案 0 :(得分:1)
如果您没有在NormalizedURLField
字段中保存非规范化的URL,则不需要覆盖to_python
和from_db_value
。保存时,改写pre_save
来转换和更新模型实例上的值:
class NormalizedURLField(models.URLField):
def pre_save(self, model_instance, add):
attr = super().pre_save(model_instance, add)
rewritten = _rewrite_internal_url(attr)
# update the value on the model instance
setattr(model_instance, self.attname, rewritten)
# return the rewritten value
return rewritten
如果从数据库中获取数据时,如果您已经在数据库中拥有要转换的非标准化值,那么您仍然需要像完成操作那样实现from_db_value
。