How to obtain the length (or count) of the data storage entities via a reference collection definition in the Google store on the client

advertisements

I have 1 to many datastore relationship between 2 Entities (google datastore) --- i.e. an instance in the Restaurant_Table can have many reviews from the Review_Table - as labeled by collection "restaurant_reviews"

As I spin through each restaurant (in a loop) to a list each of them in my template through jinja, I want to display the number or count of reviews there are for a single restaurant. All restaurants are passed from server in the form of a query from the datastore in variable restaurants as shown in the jinja2 logic in my template.

I'm getting an error that the query object TypeError: object of type 'Query' has no len(). Any other ideas on how to get the # of reviews for a single restaurant?? help!

{% for each in restaurants %}
    <script>
     var html_output = "";
     var review_count ={{each.restaurant_reviews|length}};
    ...
{% endfor %}

DATASTORE ENTITY definition is:

 class Review_Table(db.Model):
   date_submission = db.DateTimeProperty(required=True, indexed=True)
   course_id = db.ReferenceProperty(Restaurant_Table,
             indexed=True, collection_name='restaurant_reviews')


To get the number of entities represented by the query you can use the count method:

db.Query(Kind).count()

You can't do this within a jinja template -- you would need to build your output in your handler, and then render to your template.

However, as the docs say the .count() method "is faster by a constant factor than actually retrieving all of the results, but the running time still scales linearly with the sum of offset + limit." Meaning, this could get really, really slow if you get a large number of restaurants/ reviews.

A better option, in my opinion, would be to add an extra property to your Restaurants model "num_reviews", which your handler would update every time a new review is added -- making very slightly more expensive/slower writes would become hugely cheaper/faster reads because no extra querying would have to be done.