colin_dev256 colin_dev256 - 1 month ago 13
AngularJS Question

Datastore One-to-Many Google App Engine

I'm struggling to display my array items in the template. Just started with Entity relationships in GAE and I'm not finding suitable solutions on SO. Do i have to perform a query first in my handler. if so, how coz I'm struggling with the logic.

Datastore

Project
entities example display

enter image description here

Datastore
Employees
entities example display

enter image description here

Project.py

class Project(ndb.Model):
projectID = ndb.IntegerProperty(required=True)
title = ndb.StringProperty(required=True)
description = ndb.StringProperty(required=True)
startAt = ndb.DateTimeProperty(indexed=True)
endAt = ndb.DateTimeProperty()
isFullDay = ndb.BooleanProperty()
days = ndb.KeyProperty(kind='CompanyDay', repeated=True)
employees = ndb.KeyProperty(kind='Employees', repeated=True)
client = ndb.KeyProperty(kind='Client')

class Employees(ndb.Model):
name = ndb.StringProperty()
role = ndb.StringProperty()


template

data
is fetched from the backend through angular's
http
service

<md-content class="md-padding projects" layout="row" layout-wrap>
<md-card ng-repeat="data in controller.projects" flex="20" ng-click="editProject(data)">
<img src="" alt="">
<md-card-content>
<div class="project-info">
<h2 class="md-title">{{ data.title }}</h2>
<p>{{ data.description }}</p>
<p>{{ data.employees }}</p>

</div>
</md-card-content>
</md-card>
</md-content>


python code that responds to /comments

class commentsJsonHandler(webapp2.RequestHandler):
@classmethod
def route(cls):
"""
name: index, template: /
"""
return webapp2.Route('/comments', handler=cls, name='_commments_')

def get(self):
projects = Project.query()

def date_handler(obj):
print obj
if isinstance(obj, datetime):
return obj.isoformat()
else:
return str(obj)

self.response.out.write(json.dumps([dict(proj.to_dict(), **dict(id=proj.key.id())) for proj in projects], default=date_handler))


from angular - code that reguests from server

var vm = this;
vm.projects = [];
$http.get('/comments')
.then(function(result) {
console.log(result);
vm.projects = result.data;
});


Displaying employees as from the datastore.

enter image description here

Answer

You could change your date_handler to handle ndb.Key to properly render your Employee collection in your returned json

def date_handler(obj):
    print obj
    if isinstance(obj, datetime):
        return obj.isoformat()
    elif isinstance(obj, ndb.Key):
      return obj.get().to_dict()
    else:
        return str(obj)

You may want to change the name of this method as it is not just doing date_handling any more