开发者

in gql (appengine), how do i check if an entity exists matching 2 filters before inserting a new one?

the 2 filtered fields would actually be a unique index in sql so i want to see if an entity exists based on these 2 fields 开发者_如何学运维before inserting a new one.

currently i have:

t2get = db.GqlQuery("SELECT __key__ FROM Talk2 WHERE ccc = :1 AND ms = :2", c, theDay)
for x in t2get:
    theKey = x[0]
if theKey:
    t2 = Talk2.get(theKey)
else:
    t2 = Talk2()

which errors with:

UnboundLocalError: local variable 'theKey' referenced before assignment

if the entity doens't exist.

Any ideas?


If the two fields would actually be a unique index, maybe you should instead use them as the key_name. It will be faster and you can use a transaction, if needed.

def txn():
  key_name = "%d.%d." % (c, theDay)
  t2 = Talk2.get_by_key_name(key_name)
  if not t2:
    t2 = Talk2(key_name=key_name)
    t2.put()

db.run_in_transaction(txn)


d'uh I figured it out. After hours trawling the web, 10 more minutes finds me the answer:

t2 = Talk2.all().filter('ccc =', c).filter('ms =', theDay).get()

returns the first entity (if any) ready to be edited.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜