问题
I'm trying to create an ndb model where each record has an unique field "name". I would like to define this field as the key_name field and use it to look up the records. Do I have to include a name field or can I somehow set the key_name field to an arbitrary string that the user can specify as long as it's unique?
I'm thinking of using Model.get_or_insert to make sure that old records don't get overwritten, but is there a way to tell if the return value is newly created or pre-existing? I want to be able to display an error message if the user entered a duplicate name.
Lastly, I tried to create a key_name field on a DjangoForms model that uses the above ndb model as the metaclass so I can use djangoforms for validation/rendering but for some reason my defined fields don't show up.
class UserProfileForm(djangoforms.ModelForm): key_name = djangoforms.StringProperty() class Meta: model = UserProfile
回答1:
Do I have to include a name field or can I somehow set the key_name field to an arbitrary string that the user can specify as long as it's unique?
You can pass your your unique key name as the id
parameter to model constructor: profile = UserProfile(id='my_unique_name')
.
I'm thinking of using Model.get_or_insert to make sure that old records don't get overwritten, but is there a way to tell if the return value is newly created or pre-existing? I want to be able to display an error message if the user entered a duplicate name.
Use Model.get_by_id()
. It will return a model instance or None
if a model is not found:
profile = UserProfile.get_by_id('my_unique_name')
if profile:
# display error message saying that the user already exists.
Lastly, I tried to create a key_name field on a DjangoForms model that uses the above ndb model as the metaclass so I can use djangoforms for validation/rendering but for some reason my defined fields don't show up.
I don't know how DjangoForms work, but most likely they are not compatible with NDB. You will want to create your own validation logic.
来源:https://stackoverflow.com/questions/10215676/whats-the-best-way-to-specify-a-key-name-for-app-engine-ndb-model