如何对Google App Engine Datastore查询的引用对象进行排序?

3

我有一些对象称为展览对象,它们引用存储在Google App Engine数据存储中的画廊对象。

当我开始迭代这些值(最终在Django模板中)时,如何对每个画廊对象上的展览集合进行排序?

即,以下内容不起作用:


class Gallery(db.Model):
  title = db.StringProperty()
  position = db.IntegerProperty()

class Exhibit(db.Model):
  gallery = db.ReferenceProperty(Gallery, collection_name='exhibits')
  title = db.StringProperty()
  position = db.IntegerProperty()

galleries = db.GqlQuery('SELECT * FROM Gallery ORDER BY position')
for gallery in galleries:
  gallery.exhibits.order('position')

# ... send galleries off the the Django template

在模板中渲染时,相册是按正确顺序排列的,但展品却没有。

1个回答

4

不要依赖App Engine创建的集合属性,而是需要构建自己的查询:

exhibits = Exhibit.all().filter("gallery =", gallery).order("position")

或者等价的GQL语句:

exhibits = db.GqlQuery("SELECT * FROM Exhibit WHERE gallery = :1 ORDER BY position", gallery)

如果您想从模板内部执行此操作,而不是传递展品列表,您可以在Gallery对象上定义一个简单的方法来执行此查询,并从模板引用它(例如,{{gallery.exhibits_by_position}}将在Gallery对象上执行exhibits_by_position()方法,该方法可以执行上述查询)。

如果您担心这样做的速度影响,不用担心:App Engine创建的集合属性只是语法糖。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接