Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between .get() and .fetch(1)

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

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

{% for datum in data %}

{{ datum.title }}

{{ datum.content }}
   </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

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).

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?

like image 236
AutomatedTester Avatar asked Mar 27 '10 12:03

AutomatedTester


People also ask

What does the fetch () method do?

fetch() The global fetch() method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the Response object representing the response to your request.

Is fetch a post or get?

The fetch() method: Fetch API comes with a fetch () method that allows you to fetch data from all sorts of different places and work with the data fetched. It allows you to make an HTTP request, i.e., either a GET request (for getting data) or POST request (for posting data).

Is fetch a GET request?

Fetch defaults to GET requests, but you can use all other types of requests, change the headers, and send data. Let's create a POST request. The method key will have the value 'POST' .

What is HTTP fetch?

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.


2 Answers

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.

like image 113
Nick Johnson Avatar answered Sep 30 '22 14:09

Nick Johnson


get() requires (I think) that there be exactly one element, and returns it, while fetch() returns a _list_ of the first _n_ elements, where n happens to be 1 in this case.

like image 26
Marcelo Cantos Avatar answered Sep 30 '22 13:09

Marcelo Cantos