Django:未在外键 ID 上调用 Field.to_python?
我有一个 Field 的子类:
class MyIDField(Field):
...
def to_python(self, value):
return to_base_36(value)
我将它用作主键,如下所示:
class Foo(m.Model):
id = MyIDField(primary_key=True)
class Bar(m.Model):
foo = m.ForeignKey(Foo)
然后,当我访问 Bar.foo_id
时,不会调用 MyIDField.to_python
函数:
>>> b = Bar.objects.all()[0] >>> b.foo_id 1234 >>> b.foo.id 'ya' >>>
这很烦人,有几个原因,但最重要的是因为它破坏了管理中的下拉菜单 - 他们没有选择正确的值(菜单项已经是to_python
' d,但默认值没有被to_python
'd)。
这是我做错了什么吗?或者这是 Django 的问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论