Python AppEngine通过两个属性对查询对象排序

2024-06-12 01:43:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个模特

class Neighborhood(model) {
  name = db.StringProperty(required=True)
  city = EncodedProperty(encoder=_get_city_name)
}

我想检索所有邻域对象,并通过“name”和“city”属性对它们进行排序。起初,我试着

def retrieveAndSort()
  query=Neighborhood.all()
  query.order("name")
  query.order("city")
  return query

但经过进一步研究,GAE似乎不支持对EncodedProperty对象进行排序。然后,在使用sort()方法检索查询对象之后,我尝试在Python中对数据进行排序,但查询对象没有此方法。最后,我尝试用sorted()方法对查询对象进行排序,代码如下:

neighborhoods = sorted(neighborhoods, key=attrgetter('city', 'name'))

几乎成功了。然而,数据看起来很混乱,我收到了如下输出。你知道吗

Abu Dhabi - Al Maryah Island
Minneapolis - Montrose
Atlanta - Buckhead
Atlanta - Home Park
Atlantic City - Boardwalk
Atlantic City - Marina
...
California - Saint Helena
California - Yountville
New York City - Central Park
Charlotte - South End
Charlotte - Third End
...

我完全不知道为什么会发生这种情况,并将感谢任何可能的帮助。你知道吗

编辑: 较短的样本输出:

New York City - Meatpacking District
New York City - Brooklyn
New York City - Midtown West

Tags: 数据对象方法namecitynew排序order
2条回答

问题被标记为gae datastore,但“EncodedProperty”不是datastore属性类型。 https://cloud.google.com/appengine/docs/python/datastore/typesandpropertyclasses

模型应为:

class Neighborhood(db.model):
    name = db.StringProperty(required=True)
    city = db.StringProperty(required=True)

那么您的查询函数可以是:

def retrieveAndSort():
    """
    Returns everything in Neighborhood model alphabetically
    """
    query = db.GqlQuery('SELECT * FROM Neighborhood ORDER BY city DESC')
    for place in query:
        print "{0} - {1}".format(place.city, place.name)

我想你得把实体取出来然后分类。你知道吗

neighborhoods = Neighborhood.all().fetch(1000)
neighborhoods = sorted(neighborhoods, key=attrgetter('city', 'name'))

相关问题 更多 >