如何引用Python Elixir对象项
我正在尝试将 request.param
中的键名称交换为 Elixir 对象属性。下面,Elixir 对象 bk
是一个 Book()
,它具有属性 PrintTitle
。 PrintTitle
也以 request.param
的形式来自表单。我不想手动将所有参数映射到 Book 属性,而是希望基于简单的 if in
来映射它们。但是,它不起作用,因为我在 bk.k
处的语法或方法错误。
if len(request.params) != 0:
bk = Book()
for k, v in request.params.items():
print k, v # gives me love
bk.k = v # no love here
print 'Print Title:', bk.PrintTitle # value is None (obviously)
I am trying to swap in the key name from a request.param
for an Elixir object attribute. Below, the Elixir object bk
is a Book()
which has an attribute PrintTitle
. PrintTitle
also comes in from a form as a request.param
. Rather than manually map all the parameters to the Book attributes, I would like to map them based on a simple if in
. However, it doesn't work, because I have the wrong syntax or method at bk.k
.
if len(request.params) != 0:
bk = Book()
for k, v in request.params.items():
print k, v # gives me love
bk.k = v # no love here
print 'Print Title:', bk.PrintTitle # value is None (obviously)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,您不能仅以这种方式使用变量设置 Python 对象的属性。一种方法是使用 setattr 方法来完成此操作,例如,这里是一个粗略的示例:
此脚本的结果是:
Here I'm fake out your elixir model, and I'我只是使用
params
字典来伪造您在request.params
中获得的内容。因此,在此示例中,
setattr(bk, k, v)
几乎就是您想要使用bk.k=v
执行的操作。编辑:我应该补充一点,您需要小心使用 setattr,因为您需要首先确保参数中的密钥存在于您的数据库模型中,因为 elixer/sqlalchemy 可能不喜欢尝试设置不存在的数据库字段的值。
Unfortunately you can't just set the attribute of a Python object with a variable in this way. One way to do this is to use the
setattr
method to accomplish this, for example here is a crude example:The result of this script is:
Here I'm faking out your elixir model, and I'm just using a
params
dictionary to fake out whatever you're getting inrequest.params
.So in this example
setattr(bk, k, v)
is pretty much what you're trying to do withbk.k=v
.EDIT: I should add that you need to be careful using setattr, in that you need to be sure the key from your params exists in your db model first, as elixer/sqlalchemy may not like trying to set the value of a non-existent database field.