سؤال

So let's say I have this model:

class User(ndb.Model):
    username = ndb.StringProperty(required = True)

After a week, a few hundred User entities are created. Now I want to add another field:

class User(ndb.Model):
    username = ndb.StringProperty(required = True)
    username_lower = ndb.StringProperty() # username.lower()

I am not going to ask each user to input their the lowercase version of their existing username, so how can I occupy these fields for each User entity myself?

هل كانت مفيدة؟

المحلول 2

You could just make a script, to run once, that does this:

for user in User.query():
    user.username_lower = username.lower()
    user.put()

نصائح أخرى

Lowercase user name is actually the example used for Computed properties.

Computed properties (ComputedProperty) are read-only properties whose value is computed from other property values by an application-supplied function. The computed value is written to the Datastore so that it can be queried and displayed in the Datastore viewer, but the stored value is ignored when the entity is read back from the Datastore; rather, the value is recomputed by calling the function whenever the value is requested. For example:

class SomeEntity(ndb.Model):
  name = ndb.StringProperty()
  name_lower = ndb.ComputedProperty(lambda self: self.name.lower())

x = SomeEntity(name='Nick')

x.name = 'Nick'
assert x.name_lower == 'nick'
x.name = 'Nickie'
assert x.name_lower == 'nickie'

https://developers.google.com/appengine/docs/python/ndb/properties#computed

As you have no stored value for the early models it does not matter that it is not present, as it is not used directly anyway.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top