Reputation: 8060
I am trying to set an attribute to my model,
class Foo(ndb.Model):
name = ndb.StringProperty()
foo.special_name = "don't persist this"
AFAIK, I can't set attributes of ndb.Model classes that are not fields.
I am afraid to use ndb.Expando because I am worried that this object will get persisted and special_name
will be saved to my database.
What's the cleanest way to add temporary disposable value to foo
?
EDIT:
>>> class Foo(ndb.Model):
name = ndb.StringProperty()
>>> f = Foo()
>>> f.put()
Key('Foo', 26740114379063)
>>> f.bar = 123
>>> f
Foo(name=None)
>>> f.bar
Traceback (most recent call last):
File "/base/data/home/apps/shell/1.335852500710379686/shell.py", line 267, in get
exec compiled in statement_module.__dict__
File "<string>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'bar'
>>> setattr(f, 'bar', 123)
>>> f
Foo(name=None)
>>> f.bar
Traceback (most recent call last):
File "/base/data/home/apps/shell/1.335852500710379686/shell.py", line 267, in get
exec compiled in statement_module.__dict__
File "<string>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'bar'
>>> setattr(f, 'bar', 123)
>>> getattr(f, 'bar')
Traceback (most recent call last):
File "/base/data/home/apps/shell/1.335852500710379686/shell.py", line 267, in get
exec compiled in statement_module.__dict__
File "<string>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'bar'
Upvotes: 1
Views: 168
Reputation: 599610
"I can't set attributes of ndb.Model classes that are not fields."
Why would you think this? Model instances are just objects, and like any other object in Python [*], you can set arbitrary attributes on them as much as you like.
[*]: (as long as the class doesn't define __slots__
, which ndb.Model doesn't)
Upvotes: 2