0
ForeignKey 모델 필드를 확장하는 예제를 제공 할 수 있습니까? 나는이 같은 시도 :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가 없음 값으로 호출하고 외래 키는 null이 될 수 없다는됩니다. 내가 models.Field에서 상속을 받으면 작동하지만 외래 키는 아닙니다. 어떻게 모델의 기능을 확장 할 수 있는지보고 싶습니다 .ForeignKey. 감사.
호환 가능합니까? 아니면 이것을 무시하도록 강제 할 수 있습니까? – andunhill