Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does Django's custom model field method to_python get anything other than an instance?

From the documentation for to_python:

As a general rule, [to_python] should deal gracefully with any of the following arguments:

  • An instance of the correct type (e.g., Hand in our ongoing example).
  • A string (e.g., from a deserializer).
  • Whatever the database returns for the column type you're using.

I'm looking at my test coverage (using coverage.py), and the bit of code at the top of my to_python:

def to_python(self, value):
    if isinstance(value, Hand):
        return value

    # More code for handling strings below (I never get here)

is the only bit of my to_python method that gets called. What else should I be testing? I've tested saving and retrieving objects from the database, and I've tested serialization like this:

   cereal = serializers.serialize('json',
                                   Hand.objects.all())
   objects = list(serializers.deserialize("json", cereal))
like image 332
Dominic Rodger Avatar asked Dec 18 '25 16:12

Dominic Rodger


1 Answers

I've found one place where to_python ends up with something other than an instance - in the case where the value is not provided (for example, if your field is set up to allow null). In that case, because I'd implemented get_prep_value badly, to_python got passed a string containing None.

like image 75
Dominic Rodger Avatar answered Dec 23 '25 15:12

Dominic Rodger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!