我正在尝试为我的模型设置属性
class Foo(ndb.Model):
name = ndb.StringProperty()
foo.special_name = "don't persist this"
AFAIK,我无法设置非字段的ndb.Model类的属性。
我害怕使用ndb.Expando,因为我担心这个对象会被持久化,special_name
会被保存到我的数据库中。
为foo
添加临时可支配价值的最简洁方法是什么?
编辑:
>>> 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'
答案 0 :(得分:2)
“我无法设置非字段的ndb.Model类的属性。”
你为什么这么想?模型实例只是对象,就像Python [*]中的任何其他对象一样,您可以根据需要在它们上设置任意属性。
[*] :(只要该类没有定义__slots__
,ndb.Model没有定义)