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
This is a Python 3 version of the ndb client library for use with Google Cloud Datastore. The original Python 2 version was designed specifically for the Google App Engine python27 runtime.
Google App Engine (GAE) is a service for developing and hosting Web applications in Google's data centers, belonging to the platform as a service (PaaS) category of cloud computing.
An entity has one or more named properties, each of which can have one or more values. Entities of the same kind do not need to have the same properties, and an entity's values for a given property do not all need to be of the same data type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With