我一直在查看docs中的代码示例:
import re
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import gettext_lazy as _
def parse_hand(hand_string):
"""Takes a string of cards and splits into a full hand."""
p1 = re.compile('.{26}')
p2 = re.compile('..')
args = [p2.findall(x) for x in p1.findall(hand_string)]
if len(args) != 4:
raise ValidationError(_("Invalid input for a Hand instance"))
return Hand(*args)
class HandField(models.Field):
# ...
def from_db_value(self, value, expression, connection):
if value is None:
return value
return parse_hand(value)
def to_python(self, value):
if isinstance(value, Hand):
return value
if value is None:
return value
return parse_hand(value)
据我所知,from_db_value()
负责将来自数据库的字符串转换为正确的python类型(如果我错了,请纠正我)。 to_python()
也负责将字符串值转换为python类型。如果我们看一下这个例子,这两个函数会做类似的事情。不,不是完全相同的东西,但非常相似。
我的问题:
to_python()
必须能够处理value = Hand()
?我认为这是为了将字符串转换为Hand
个对象。为什么from_db_value()
不需要能够处理此案例?