数据存储一对多Google App Engine

时间:2016-11-08 11:12:31

标签: python angularjs google-app-engine google-cloud-datastore

我很难在模板中显示我的数组项。刚开始使用GAE中的实体关系,我没有在SO上找到合适的解决方案。我是否必须先在我的处理程序中执行查询。如果是这样,我是如何努力的。

数据存储区 Project个实体示例显示

enter image description here

数据存储区 Employees个实体示例显示

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

模板

data 是通过angular的 http 服务

从后端获取的
 <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>

响应/ comments

的python代码
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)) 
来自angular的

- 来自服务器的请求

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

从数据存储区显示员工。

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以更改date_handler以处理ndb.Key,以便在返回的json中正确呈现Employee集合

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)

您可能想要更改此方法的名称,因为它不仅仅是执行date_handling