不增加谷歌应用程序引擎数据库值
-
22-09-2019 - |
题
下面是一些代码不工作它是如何工作的。每次查询数据库的时候,我得到无论是对选项的0或1的值,并在数据库中的值不增加,即使因为你可以看到,在管线86和89,该值递增。任何想法,这是怎么回事了?我使用谷歌应用程序引擎的Django。
user_result = request.POST['json']
65 user_result = json.loads(user_result)
66 user_country = get_user_country(user_result)
67 question_number = get_question_number(user_result)
68 answered_option = get_answered_option(user_result)
69
70 country_option_1 = 0
71 country_option_2 = 0
72 world_option_1 = 0
73 world_option_2 = 0
74
75 """
76 Get already existing record for the question for the contry, or create
77 new one and put/update in db
78 """
79
80 country_wide_data = db.GqlQuery("SELECT * FROM CountryWideData WHERE country = :1 AND questionNo = :2", user_country, question_number)
81 flag = False
82 for i in country_wide_data:
83 flag = True
84 if flag:
85 if answered_option==1:
86 country_wide_data[0].optionOne = country_wide_data[0].optionOne + 1
87
88 elif answered_option==2:
89 country_wide_data[0].optionTwo = country_wide_data[0].optionTwo + 1
90 country_option_1 = country_wide_data[0].optionOne
91 country_option_2 = country_wide_data[0].optionTwo
92 country_wide_data[0].put()
93 else:
94 country_wide_data = CountryWideData(country=user_country, questionNo=question_number)
95
96 if answered_option==1:
97 country_wide_data.optionOne = 1
98 country_wide_data.optionTwo = 0
99 elif answered_option==2:
100 country_wide_data.optionOne = 0
101 country_wide_data.optionTwo = 1
102 country_option_1 = country_wide_data.optionOne
103 country_option_2 = country_wide_data.optionTwo
104 country_wide_data.put()
解决方案
您永远不会使用的取(),以实际执行GqlQuery您在80行创建。
尝试这种情况:
country_wide_data = db.GqlQuery("SELECT * FROM CountryWideData WHERE country = :1 AND questionNo = :2", user_country, question_number).fetch()
顺便说一句,你要想做一个交易的这种递增内;否则,你会得到一个竞争条件,如果有多个请求,可以执行这个代码,并计数不准确。对交易的文档是在这里: http://code.google.com /appengine/docs/python/datastore/transactions.html
一般情况下,你将要采取的创建或更新这些实体的代码,并把它们放到功能,像这样:
def increment_existing_data(key, answered):
cwd_to_incr = db.get(key)
if answered == 1:
cwd_to_incr.optionOne += 1
elif answered == 2:
cwd_to_incr.optionTwo += 1
cwd_to_incr.put()
def create_new_data(answered, user_country, question_number):
new_data = CountryWideData(country=user_country, questionNo=question_number)
if answered == 1:
new_data.optionOne = 1
new_data.optionTwo = 0
elif answered == 2:
new_data.optionOne = 0
new_data.optionTwo = 1
new_data.put()
然后,可以使用的 db.run_in_transacation 方式,这样调用这些函数:
country_wide_data = db.GqlQuery("SELECT * FROM CountryWideData WHERE country = :1 AND questionNo = :2", user_country, question_number).get()
if country_wide_data is not None:
db.run_in_transaction(increment_existing_data, country_wide_data.key(), answered_option)
else:
db.run_in_transaction(create_new_data, answered_option, user_country, question_number)
不隶属于 StackOverflow