GAE 使用 Python(一对多)将数组发布到数据存储

GAE posting an array to the datastore with Python (One to Many)

使用 GAE 已经有几个月了。这是我第一次在这里处理一对多关系。在我开始处理关系之前,一切都已 post 很好地传输到数据存储区。这是第一个。有人可以帮我 'post' 到数据存储区吗?目前,文档和其他示例非常混乱。 employees=r['Employees'], 我知道我做错了我只想先简单 post。如果你能把它弄得更好!如图所示,posting 时出现 BadValueError;

model.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()
    employees = ndb.KeyProperty(kind='Employees', repeated=True)

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

handlers.py

 def post(self):
    r = json.loads(self.request.body) 
    print str(r)

    g = Project(projectID=int(r['ProjectID']),  
                description=r['Description'],
                title=r['Title'],
                employees=r['Employees'],
                startAt=datetime.strptime(r['StartAt'], '%d/%m/%Y %H:%M %p'),
                endAt=datetime.strptime(r['EndAt'], '%d/%m/%Y %H:%M %p'))

    project_key = g.put()
    project_key.get()
    print project_key

controller.js

    $scope.employees = [
                            {
                                name:'mark',
                                role: 'dev'
                            }, 
                            {
                                name:'colin',
                                role: 'dev2'
                            }, 
                       ];

更新------------------------------------- ------------------------------

json处理程序

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


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

    def date_handler(obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        else:
            raise TypeError

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

您必须遍历 json 负载中的员工集合并首先创建这些员工实体,然后使用它们的键创建项目实体

def post(self):
    r = json.loads(self.request.body)
    print str(r)
    employee_keys = []
    for emp in r['Employees']:
        employee = Employees(name=emp['name'], role=emp['role'])
        employee.put()
        employee_keys.append(employee.key)


    g = Project(projectID=int(r['ProjectID']),
                description=r['Description'],
                title=r['Title'],
                employees=employee_keys,
                startAt=datetime.strptime(r['StartAt'], '%d/%m/%Y %H:%M %p'),
                endAt=datetime.strptime(r['EndAt'], '%d/%m/%Y %H:%M %p'))

    project_key = g.put()
    project_key.get()
    print project_key