1

我只是想知道这样做的正确方法是什么。我有一个包含浮点数的数据库,我只是想获取数据库中所有浮点数的总和。

例子:

class Sum_DB(db.Model):
    name_of_profile = db.StringProperty(required = True)
    float_value= db.FloatProperty()


sum_me_up  = db.GqlQuery("select * from Sum_DB WHERE name_of_profile =:1", profile_id)

如果有人能在这里帮我一把,我将不胜感激。我尝试过使用 fetch() 但无法获得总和或值列表。

4

2 回答 2

2

Sorry if I'm misunderstanding, but it sounds like you want to retrieve a group of entities from the datastore and sum their respective float_value properties. If that is what you want to do, you will need to set up a query that pulls all of the entities in question (here we will just use Sum_DB.all() to pull all of them) and then iterate through the returned list of objects, summing their float_value property. For example:

class Sum_DB(db.Model):
    name_of_profile = db.StringProperty(required = True)
    float_value= db.FloatProperty()


class MainHandler(webapp2.RequestHandler):
  def get(self, *args, **kwargs):
    r = Sum_DB(name_of_profile='test1', float_value=float(1.2359))
    s = Sum_DB(name_of_profile='test2', float_value=float(2.2355))
    t = Sum_DB(name_of_profile='test3', float_value=float(4.2185))

    r.put()
    s.put()
    t.put()

    # Using the Query class
    query = Sum_DB.all()

    # You can now iterate over that 'query', with each element
    # representing an entity from your datastore. Each entity
    # will have the properties you defined in Sum_DB, so you 
    # can access them by name.
    sum_me_up = sum(result.float_value for result in query)

    # Or using GQL - the concept/result is the same
    query2 = db.GqlQuery('SELECT * from Sum_DB')
    sum_me_up2 = sum(result.float_value for result in query2)

    self.response.out.write('Query: {0} | GQL: {1}'.format(sum_me_up,
                                                           sum_me_up2))


app = webapp2.WSGIApplication([
                   ('/', MainHandler),
                   ],
                   debug=True)
于 2012-12-06T05:58:29.517 回答
0

The mapreduce pipeline makes it easy to sum across arbitrarily large entities: https://developers.google.com/appengine/docs/python/dataprocessing/overview

You just write a mapper to sum what you want.

于 2012-12-09T16:10:13.063 回答