Google app engineデータベースの値になincrementing
-
22-09-2019 - |
質問
ここにはあるコードがうまくいきませんかとなっています。毎回のデータベースが照会されるかのいずれかが0又は1の値をオプションの値のデータベースな増加もとで、86 89の価値が増加されます。うえおかしい。を使用していDjango Google App engine.
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()
解決
決してない使用 fetch() 実際に実行しGqlQuery作成するに80.
してみてください:
country_wide_data = db.GqlQuery("SELECT * FROM CountryWideData WHERE country = :1 AND questionNo = :2", user_country, question_number).fetch()
ちなみに、かりにくいこincrementing内の取引;その他、レースの条件により多くの要求を行うことができ、このコードをカウントが誤りである。の取引はこちら: 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