NDB 按重复 StructuredProperty 的特定实例的 属性 排序

NDB ordering by property of specific instance of repeated StructuredProperty

在一个汽车历史应用程序中,我必须创建不同的图表,其中某些模型可能出现在一个或多个不同的图表中,如 "fastest car"、"best car" 等。然后它们必须是在图表中订购。我使用 StructuredProperty 创建标签 name/order 位置对。

class CarTag(ndb.Model):
    name = ndb.StringProperty()
    position = ndb.IntegerProperty()

class Car(ndb.Model):
    model_name = ndb.StringProperty()
    trim = ndb.StringProperty()
    year = ndb.IntegerProperty()
    tags = ndb.StructuredProperty(CarTag, repeated=True)

结构化过滤器 属性 工作正常。

cars = Car.query(Car.tags.name=="fastest car")

但要获得有序图表,我需要按名称为 "fastest car" 的同一 StructuredProperty 的位置 属性 对它们进行排序。正如我在 this question 中所读,order(Car.tags.position) 将仅按列表的第一个元素排序。

cars = Car.query(Car.tags.name==name).order(Car.tags.position)

是否可以通过特定 StructuredProperty 的 属性 进行订购?

这并不是说您不能通过 StructuredProperty 内部的 属性 进行排序,而是您的 StructuredProperty 是 repeated=True... 使其成为一个列表-属性.. 而您无法可靠地对列表进行排序-属性:

https://cloud.google.com/appengine/docs/python/datastore/queries#properties_with_multiple_values_can_behave_in_surprising_ways

Properties with multiple values can behave in surprising ways

Because of the way they're indexed, entities with multiple values for the same property can sometimes interact with query filters and sort orders in unexpected and surprising ways.

.....

If the query results are sorted in ascending order, the smallest value of the property is used for ordering. If the results are sorted in descending order, the greatest value is used for ordering. Other values do not affect the sort order, nor does the number of values. This has the unusual consequence that an entity with property values 1 and 9 precedes one with values 4, 5, 6, and 7 in both ascending and descending order.