get_or_insert,如何知道它是创建还是检索?
我想使用 get_or_insert,但我怎么知道它只是创建或从现有条目中获取。
I want to use get_or_insert, But how do I know that it's just created or fetched from existing entries.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简而言之,你不能。不过,
get_or_insert
只是一个方便的函数,您可以轻松地自己编写和改进。这是一个简单的替换,它返回一个元组,指示它是否已创建:以下是使用它的方法:
请记住,如果您将它与上面的配方一起使用,则您所做的任何事情都将基于该实体是否是新的or not 不是事务性的 - 您的代码可能会在创建实体之后但执行此操作之前失败。如果您想做的事情有副作用,您可能应该在事务内进行。
In a nutshell, you can't.
get_or_insert
is just a convenience function, though, and one you can write and improve for yourself quite easily. Here's a simple replacement that returns a tuple, indicating if it was created or not:And here's how you'd use it:
Just bear in mind that if you use it with the recipe above, anything you do based on whether the entity is new or not is not transactional - your code could fail after creating the entity but before doing that. If what you want to do has side-effects, you should probably do it inside the transaction.