简体   繁体   中英

NDB ordering by property of specific instance of repeated StructuredProperty

In a an app for cars history I have to create different charts where some models may be present in one or more different charts as "fastest car", "best car", etc. Then they have to be ordered in the chart. I have used StructuredProperty to create tag name/order position pairs.

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)

The filter on the structured property works fine.

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

But to get the ordered chart I need to order them by the position property of the same StructuredProperty which name is "fastest car". As I read in this question order(Car.tags.position) will order only by the first element of the list.

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

Is it possible to order by property of specific StructuredProperty?

It's not that you can't order by a property inside of a StructuredProperty, it's that your StructuredProperty is repeated=True... making it a list-property.. and you can't reliably sort on a list-property:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM