python .get() 和 .fetch(1) 有什么区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2529198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between .get() and .fetch(1)
提问by AutomatedTester
I have written an app and part of it is uses a URL parser to get certain data in a ReST type manner. So if you put /foo/bar as the path it will find all the bar items and if you put /foo it will return all items below foo
我编写了一个应用程序,其中一部分是使用 URL 解析器以 ReST 类型的方式获取某些数据。因此,如果您将 /foo/bar 作为路径,它将找到所有 bar 项目,如果您将 /foo 放入,它将返回 foo 以下的所有项目
So my app has a query like
所以我的应用程序有一个查询
data = Paths.all().filter('path =', self.request.path).get()
Which works brilliantly. Now I want to send this to the UI using templates
哪个工作得很好。现在我想使用模板将其发送到 UI
{% for datum in data %}
{% 用于数据中的数据 %}
{{ datum.title }}
{{ 数据.title }}
{{ 数据内容}} </div>
{% endfor %}
{% 结束为 %}
When I do this I get data is not iterable error. So I updated the Django to {% for datum in data.all %}
which now appears to pull more data than I was giving it somehow. It shows all data in the datastore which is not ideal. So I removed the .all from the Django and changed the datastore query to
当我这样做时,我得到数据不是可迭代的错误。所以我更新了 Django,{% for datum in data.all %}
它现在似乎提取了比我以某种方式提供的数据更多的数据。它显示了数据存储中不理想的所有数据。所以我从 Django 中删除了 .all 并将数据存储查询更改为
data = Paths.all().filter('path =', self.request.path).fetch(1)
which now works as I intended. In the documentation it says
现在按我的意图工作。在文档中它说
The db.get() function fetches an entity from the datastore for a Key (or list of Keys).
db.get() 函数从数据存储中获取一个实体以获得一个键(或键列表)。
So my question is why can I iterate over a query when it returns with fetch()
but can't with get()
. Where has my understanding gone wrong?
所以我的问题是为什么我可以在查询返回时迭代查询fetch()
但不能使用get()
. 我的理解哪里出了问题?
采纳答案by Nick Johnson
You're looking at the docs for the wrong get() - you want the get() method on the Query object. In a nutshell, .fetch() always returns a list, while .get() returns the first result, or None if there are no results.
您正在查看错误 get() 的文档 - 您需要Query 对象上的 get() 方法。简而言之, .fetch() 总是返回一个列表,而 .get() 返回第一个结果,如果没有结果,则返回 None 。
回答by Marcelo Cantos
get() requires (I think) that there be exactly one element, and returns it, while fetch() returns a listof the first nelements, where nhappens to be 1 in this case.
get() 要求(我认为)只有一个元素,并返回它,而 fetch() 返回前n 个元素的列表,在这种情况下,n恰好是 1。