我正在开发一个应用程序,其中通过它们的键将学生
实体添加到班级
实体中。因此,在一个班级中,我可以拥有一个可由其键标识的学生列表
,这些键可以是整数或字符串。但是我不知道如何做到这一点。(请原谅我,这是我使用Python的第一个项目)以下是我的代码:
import webapp2
from webapp2_extras import json
from google.appengine.ext import ndb
registrationPage = """
<html>
<head><title>Student Registration</title><head>
<body>
<h1>Student Registration</h1>
<form action="/" method="post">
<table border="1">
<tr><td>Srudent's BannerId</td><td><input type="number" size="6" name="banner_id"/></
td></tr>
<tr><td>Student's Name</td><td><input type="text" size="50" name="name"/></td></tr>
<tr><td><input type="submit" name="submit" value="Register Student"/></td></tr>
</table>
</form>
</body>
</html>
"""
class MathClass (ndb.Model):
class_Id = ndb.IntegerProperty(required=True)
professor_name = ndb.StringProperty(required=True)
number_of_students = ndb.IntegerProperty()
students = ndb.KeyProperty(repeated=True)
# A Class can return its data in JSON format
def toJSON(self):
jsonData = {
"class_id": self.key.id(),
"teacher": self.teacher,
"number_of_students": str(self.number_of_students),
}
return json.encode(jsonData)
class Student(ndb.Model):
banner_id = ndb.IntegerProperty(required=True)
name=ndb.StringProperty()
# A Student can return its data in JSON format
def toJSON(self):
jsonData = {
"banner_id": self.key.id(),
"name": self.name,
}
return json.encode(jsonData)
def toTableRow(self, points):
return "<tr><td>" + self.key.id() + "</td><td>" + self.name + "</td></tr>"
class StudentHandler(webapp2.RequestHandler):
def post(self):
banner_id = self.request.get('banner_id')
callback = self.request.get('callback')
student = Student.get_by_id(banner_id)
if student: # This student name already exists.
self.error(409) # This is the HTTP status code for 'unable to process due to conflict'
else:
id = int(self.request.get('banner_id'))
i = int(self.request.get('banner_id'))
n = self.request.get('name')
student = Student(id=banner_id, banner_id = id, name=n)
student.put()
if callback:
self.response.write(callback + '(' + student.toJSON + ')')
else:
self.response.write(student.toJSON())
class RegistrationHandler(webapp2.RequestHandler):
def get(self):
self.response.write(registerationPage)
app = webapp2.WSGIApplication([
('/', StudentHandler),
('/reg', RegistrationHandler)
], debug=True)
通过使用HTML表单,我已经成功保存了一个Student
实体到我的本地数据存储中。但是现在我遇到了困难:如何创建一个包含刚刚创建的学生作为成员的班级实体?