I need to check if the item is in datastore before I update it.
I have 2 lists: UNIQUES = ["B","K","V"] and COUNTS = [5, 10, 3]
This is the model:
class Rep(db.Model):
mAUTHOR = db.UserProperty(auto_current_user=True)
mUNIQUE = db.TextProperty()
mCOUNT = db.IntegerProperty()
mDATE = db.DateTimeProperty(auto_now_add=True)
This function updates the database:
def write_to_db(S, C):
REP = Rep(mUNIQUE=S, mCOUNT=C)
db.put(REP)
Inspired by this page I try:
for i in range(len(UNIQUES)):
C_QUERY = Rep.all()
C_QUERY.filter("mAUTHOR =", user)
C_QUERY.filter("mUNIQUE =", UNIQUES[i])
C_RESULT = C_QUERY.fetch(1)
if C_RESULT:
C = C_RESULT.mCOUNT + COUNTS[i]
S = db.Text(UNIQUES[i])
write_to_db(S,C)
else:
C = COUNTS[i]
S = UNIQUES[i]
write_to_db(S, C)
But the result is not what I expect. C_RESULT is always empty; and instead of updating, a new record is created. What am I doing wrong? Thanks!
EDIT3: Problem solved
As per David Underhill’s comment I updated the code and it now works.
if C_RESULT:
rep=C_RESULT[0]
rep.mCOUNT+=COUNTS[i]
rep.put()
EDIT2: Related question
How do I update this query and put it back with updated information?
C_QUERY = Rep.all()
C_QUERY.filter("mAUTHOR =", user)
C_QUERY.filter("mUNIQUE =", UNIQUES[i])
C_RESULT = C_QUERY.fetch(1)
I want to change mCOUNT and then write it to datastore. How do I this? This looks like the exact same thing they do in this page but I could not make it work. Thanks for your help.
EDIT
I updated the code per David Underhill’s answer. That solved the problem (but the functionality is not right. I am not sure if that should be a different question).
for i in range(len(UNIQUES)):
C_QUERY = Rep.all()
C_QUERY.filter("mAUTHOR =", user)
C_QUERY.filter("mUNIQUE =", UNIQUES[i])
C_RESULT = C_QUERY.fetch(1)
if C_RESULT:
C = C_RESULT[0].mCOUNT + COUNTS[i]
S = UNIQUES[i]
write_to_db(S, C)
else:
C = COUNTS[i]
S = UNIQUES[i]
write_to_db(S, C)
The problem is that the query is trying to filter
mUNIQUE. However, you declaredmUNIQUEas adb.TextPropertywhich is never indexed. As a result, you query never finds any results.Solution: Change
mUNIQUEto adb.StringProperty(which is indexed by default).You should also consider updating
Repin a transaction – the current code may fail to property addCOUNTS[i]if two requests try to update the same entity concurrently.Also, you can update
S = db.Text(UNIQUES[i])to simplyS = UNIQUES[i].