我正在学习python和GAE。我已经能够构建一个基本的应用程序,但我遇到了意外的重复条目。我不确定,但我认为我可以通过使用一个关键名称来解决这个问题,但我仍然在学习,并且对我发现的解释关键名称的例子感到困惑。
我想要做的是使用字符串作为“条目ID”,以便在发布条目之前,脚本确保不存在具有相同条目“idstring”的条目。我已经构建了一些混乱的代码来构建列表并检查列表中的条目,但我怀疑有更有效的方法来执行此操作?
这是我的代码:
import webapp2
from google.appengine.ext import db
class Options(db.Model):
idstring = db.StringProperty()
content = db.StringProperty(multiline=True)
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
options = db.GqlQuery("SELECT * "
"FROM Options "
"LIMIT 10")
for entry in options:
self.response.out.write('%s ' % entry.idstring)
self.response.out.write('Content: %s <br>' % entry.content)
self.response.out.write("""
<form action="/sign" method="post">
<div class="field-field">
<select name="idstring" id="id_string">
<option value="unique1">ID1</option>
<option value="unique2">ID2</option>
<option value="unique3">ID3</option>
</select>
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Submit"></div>
</form>
</body>
</html>""")
class Optionbook(webapp2.RequestHandler):
def post(self):
idlist = Options.all()
idlist2 = []
for i in idlist:
idlist2.append(i.idstring)
idstring = self.request.get('idstring')
if idstring not in idlist2:
entry = Options()
entry.content = self.request.get('content')
entry.idstring = self.request.get('idstring')
entry.put()
self.redirect('/')
app = webapp2.WSGIApplication([
('/', MainPage),
('/sign', Optionbook)
], debug=True)
答案 0 :(得分:0)
回想起来,解决方案非常简单。向数据存储区添加条目时,数据存储区可以使用实体key_id或key_name作为密钥。如果您想使用密钥名称,只需将key_name = yourkeystring添加到您的代码:
import webapp2
from google.appengine.ext import db
class Options(db.Model):
idstring = db.StringProperty()
content = db.StringProperty(multiline=True)
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
options = db.GqlQuery("SELECT * "
"FROM Options "
"LIMIT 10")
for entry in options:
self.response.out.write('Content: %s <br>' % entry.content)
self.response.out.write("""
<form action="/sign" method="post">
<div class="field-field">
<select name="yourkeystring" id="yourkeystring">
<option value="ID1">ID1</option>
<option value="ID2">ID2</option>
<option value="ID3">ID3</option>
</select>
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Submit"></div>
</form>
</body>
</html>""")
class Optionbook(webapp2.RequestHandler):
def post(self):
n = Options(
content = self.request.get('content'),
key_name = self.request.get('yourkeystring'))
n.put()
self.redirect('/')
app = webapp2.WSGIApplication([
('/', MainPage),
('/sign', Optionbook)
], debug=True)