to_python()和from_db_value()方法在函数中重叠?

时间:2017-12-28 13:04:05

标签: python django

我一直在查看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类型。如果我们看一下这个例子,这两个函数会做类似的事情。不,不是完全相同的东西,但非常相似。

我的问题:

  1. 在这个领域有两个非常相似的方法是什么原因?
  2. 为什么to_python()必须能够处理value = Hand()?我认为这是为了将字符串转换为Hand个对象。为什么from_db_value() 需要能够处理此案例?

0 个答案:

没有答案