是否可以在 App Engine 模型中动态命名属性?
setattr
允许您动态命名 Python 类中的属性。我正在尝试对 App Engine 模型执行类似的操作:
class MyModel(db.Model):
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
# Doesn't fully work
setatr(self, 'prop1', db.ListProperty(db.Key))
setatr(self, 'prop2', db.StringListProperty())
# Works fully
# prop1 = db.ListProperty(db.Key))
# prop2 = db.StringListProperty())
此代码可以编译,但是当我稍后调用 model.prop1.append(key)
时,我收到此错误:
AttributeError: 'ListProperty' object has no attribute 'append'
我怀疑这是因为prop1
在模型中声明,而不是 self.prop1
,但我不完全理解语法的意义。
有谁做到了这一点,或者有人对语法差异有任何见解吗?
setattr
allows you to dynamically name attributes in Python classes. I'm trying to do something similar with an App Engine Model:
class MyModel(db.Model):
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
# Doesn't fully work
setatr(self, 'prop1', db.ListProperty(db.Key))
setatr(self, 'prop2', db.StringListProperty())
# Works fully
# prop1 = db.ListProperty(db.Key))
# prop2 = db.StringListProperty())
This code compiles, but when I call model.prop1.append(key)
later on, I get this error:
AttributeError: 'ListProperty' object has no attribute 'append'
I suspect this is because prop1
is declared in models instead of self.prop1
, but I don't fully understand the syntax's significance.
Has anyone accomplished this, or does anyone have any insight into syntactic differences?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您正在寻找
db.Expando
类(而不是db.Model
)。I think you're looking for the
db.Expando
class (instead ofdb.Model
).这个问题:
给出了您想要执行的操作的示例。
This SO question:
gives an example of what you want to do.
不确定,但这可能有效:
Not sure but would this work maybe: