How to create random default value in ndb model in GAE?
<p>I have a ndb model</p>

<pre><code>import os
class ProblemInvite(ndb.Model):
    email = nab.StringProperty(required=True)
    token = ndb.StringProperty(required=True, default=os.urandom(16).encode('hex'))
</code></pre>

<p>When I create a list of the model, the token is same:</p>

<pre><code>import logging
for email in emails:
    problem_invite = ProblemInvite(email=email_address)
    logging.exception(problem_invite.token)
</code></pre>

<p>The weird thing is, the invite token for each email is same, what's wrong with it? Thanks.</p>

<p>There can only be <strong>one</strong> default value for a property type in the datastore at a time. From the <a href="https://cloud.google.com/appengine/docs/python/ndb/entity-property-reference#options" rel="nofollow">Property Options</a> table:</p>

<p><a href="https://i.stack.imgur.com/k2kBU.png" rel="nofollow"><img src="https://i.stack.imgur.com/k2kBU.png" alt="enter image description here"></a></p>

<p>So your <code>os.urandom(16).encode('hex')</code> expression is evaluated only once. I'm not 100% certain when, but I suspect it'd be at app deployment time - when the datastore models are uploaded.</p>

<p>To address the problem just drop the default value and explicitly specify the property value when you create the entity.</p>

<p><strong>Side note:</strong> when using default values in ndb models you need to be extra careful at <strong>changing these default values</strong> as the behaviour (i.e. the data returned for the affected properties) <strong>may change</strong> for the entities already existing in the datastore at app deployment/update time.</p>

python google-app-engine app-engine-ndb python-os