Django: Field.to_python not called on foreign key IDs? – Education Career Blog

I’ve got a subclass of Field:

class MyIDField(Field):
    ...
    def to_python(self, value):
        return to_base_36(value)

And I use it as a primary key like this:

class Foo(m.Model):
    id = MyIDField(primary_key=True)

class Bar(m.Model):
    foo = m.ForeignKey(Foo)

Then the MyIDField.to_python function isn’t called when I access Bar.foo_id:

>>> b = Bar.objects.all()0
>>> b.foo_id
1234
>>> b.foo.id
'ya'
>>>

This is annoying for a few reasons, but most significantly because it breaks dropdown menus in admin — they don’t select the right values (the menu items have been to_python‘d, but the default value has not been to_python‘d).

Is this something I’m doing wrong? Or is this an issue with Django?

Leave a Comment