views:

28

answers:

2

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?

A: 

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.

khany
This works, but it's not transactional - race conditions are possible here. See Robert's answer for the right way to handle this.
Nick Johnson
+1  A: 

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)
Robert Kluin
thanks Robert. that is actually how i had it previously but it didn't seem right. would that be an acceptable (as in agreeable) way to structure that table?
khany
You do not need any additional tables. The key is the entity's primary key. By building it using key_name you ensure the entity is unique. If you will always want to overwrite existing data you not even need to fetch the entity, just build the key like I showed and put the new entity.
Robert Kluin