有人可以给我一个扩展 ForeignKey 模型字段的例子吗?我试过这样:
class ForeignKeyField(forms.ModelChoiceField):
def __init__(self, *args, **kwargs):
super(ForeignKeyField, self).__init__(Chain.objects.all(), *args, **kwargs)
def clean(self, value):
return Chain.objects.get(pk=value)
class CustomForeignKey(models.ForeignKey):
description = "key from ndb"
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
super(CustomForeignKey, self).__init__(*args, **kwargs)
def db_type(self, connection):
return "ndb"
def to_python(self, value):
# import pdb; pdb.set_trace()
from google.appengine.api.datastore_types import Key
if isinstance(value, Key) is True:
return value.id()
if value is None:
return
return value
def get_db_prep_save(self, value, connection, prepared=False):
save_value = ndb.Key(API_Chain, value.id).to_old_key()
return save_value
def formfield(self, **kwargs):
return models.Field.formfield(self,ForeignKeyField, **kwargs)
我不知道为什么,但如果我使用__metaclass__ = models.SubfieldBase
to_python 调用时没有值,它说外键不能为空。如果我从 models.Field 继承,它可以工作,但不能作为外键。我想看看如何扩展models.ForeignKey 的功能。谢谢。