我有两个模型班 Team 和 Student。每个 Team 实体都有多个 Users 实体,我认为“一对多”是一个合适的模型。我这样编码:
class Team(db.Model):
teamNmae = db.StringProperty(required=True)
teamID = db.IntegerProperty(required=True)
class Users(db.Model):
name = db.StringProperty(required=True)
reference = db.ReferenceProperty(Team,collection_name=teamMembers)
按照这个文档,我需要先创建一个 Team 实体,然后创建引用设置为此 Team 实体的用户。但是,问题来了,我想先创建用户,然后用户才能创建团队。那么,当我创建一个不存在团队的用户时如何设置参考?
编辑1:
我编写了简单的代码来测试是否可以在不创建引用实体的情况下创建实体。
_author__ = 'Steven_yang'
import os
import webapp2
from google.appengine.ext import db
from google.appengine.ext.webapp import template
defaultStu = [
'qingWANG',
'stevenYANG',
'jingZHU',
'conghuiHE',
'lianDUAN',
'xinHAO'
]
class Students(db.Model):
#reference = db.ReferenceProperty(Team,collection_name='teamMember',required=False)
name = db.StringProperty(required=True)
class Team(db.Model):
teamName = db.StringProperty(required=True)
teamID = db.IntegerProperty(required=True)
def createStu():
stu_count = Students.all().count(1)
if stu_count == 0:
for stu in defaultStu:
newStu = Students(name = stu)
newStu.put()
class testReferenceHandler(webapp2.RequestHandler):
def get(self):
createStu()
self.render_page()
def render_page(self):
stus = Students.all().fetch(10)
templateValues={}
templateValues['stus'] = stus
form = os.path.join(os.path.dirname(__file__),'template/testref.html')
renderForm = template.render(form,templateValues)
self.response.out.write(renderForm)
app = webapp2.WSGIApplication([('/testref',testReferenceHandler)],debug=True)
HTML文件是:
<body>
{% for s in stus%}
<div>{{s.name}}</div>
{% endfor%}
</body>
</html>
当我注释掉 ReferenceProperty 行时,一切都很好。当我添加 ReferenceProperty 行时,出现server error。那么,如果没有之前创建的引用,我就无法创建实体?