[Python] to_python() and from_db_value() methods overlapping in function?

Discussão em 'Python' iniciado por Stack, Julho 30, 2025.

  1. Stack

    Stack Membro Participativo

    I've been looking at this code example from the 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)


    As far as I understand, from_db_value() is responsible for turning a string that's coming from the database to the right python type (please correct me if I'm wrong). to_python() is also responsible for turning a string value into a python type. If we look at the example, the two functions do similar stuff. No, not the exact same stuff, but very similar.

    My questions:

    1. What is the reason for having two very similar methods on the field?
    2. Why does to_python() have to be able to handle value = Hand()? I thought it was made for turning strings into Hand objects. Why does from_db_value() not need to be able to handle this case?

    Continue reading...

Compartilhe esta Página