Python:如何可以互换地访问对象或字典?
我正在编写一个 Django 视图,它有时从数据库获取数据,有时从外部 API 获取数据。
当它来自数据库时,它是一个 Django 模型实例。属性必须用点表示法访问。
来自 API 的数据是字典,并通过下标表示法进行访问。
无论哪种情况,都会对数据进行一些处理。
我想避免
if from_DB:
item.image_url='http://example.com/{0}'.format(item.image_id)
else:
item['image_url']='http://example.com/{0}'.format(item['image_id'])
尝试寻找一种更优雅、更干燥的方式来做到这一点。
有没有一种方法可以通过适用于字典或对象的键来获取/设置?
I'm writing a Django view that sometimes gets data from the database, and sometimes from an external API.
When it comes from the database, it is a Django model instance. Attributes must be accessed with dot notation.
Coming from the API, the data is a dictionary and is accessed through subscript notation.
In either case, some processing is done on the data.
I'd like to avoid
if from_DB:
item.image_url='http://example.com/{0}'.format(item.image_id)
else:
item['image_url']='http://example.com/{0}'.format(item['image_id'])
I'm trying to find a more elegant, DRY way to do this.
Is there a way to get/set by key that works on either dictionaries or objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 Bunch 类,它将字典转换为接受点表示法的内容。
You could use a Bunch class, which transforms the dictionary into something that accepts dot notation.
在 JavaScript 中它们是等效的(通常很有用;我提到它是为了防止您在进行 Web 开发时不知道),但在 Python 中它们是不同的 -
[items]
与>.属性
。使用
__getattr__
编写允许通过属性访问的内容很容易:然后像使用
dict
一样使用它(它将接受dict< /code> 作为参数,因为它扩展了
dict
),但您可以执行诸如item.image_url
之类的操作,它会将其映射到item.image_url< /code>,获取或设置。
In JavaScript they're equivalent (often useful; I mention it in case you didn't know as you're doing web development), but in Python they're different -
[items]
versus.attributes
.It's easy to write something which allows access through attributes, using
__getattr__
:Then just use it as you'd use a
dict
(it'll accept adict
as a parameter, as it's extendingdict
), but you can do things likeitem.image_url
and it'll map it toitem.image_url
, getting or setting.我不知道这会产生什么影响,但我会向 django 模型添加一个方法,该方法将字典读取到自身中,这样您就可以通过模型访问数据。
I don't know what the implications will be, but I would add a method to the django model which reads the dictionary into itself, so you can access the data through the model.