RedDragon
RedDragon

Reputation: 2138

How can I sort by an attribute of a key property in Google Cloud/Python?

Using the following ndb model classes:

class Product(ndb.Model):
    name = ndb.StringProperty()
    barcode = ndb.StringProperty()

class Donation(ndb.Model):
    user= ndb.UserProperty()
    product = ndb.KeyProperty(kind=Product)

When using a query such as:

donations = Donation.query().order(Donation.product).fetch(1000)

How can I sort the resulting donations by Product name or barcode?

Upvotes: 0

Views: 238

Answers (1)

Dan Cornilescu
Dan Cornilescu

Reputation: 39824

You cannot do such query, at least not with the datastore. The sort order can only be one of the respective entity model's properties.

Every query needs one or more corresponding datastore indexes. For ordered queries you need composite indexes, defined in the index.yaml file. Each such index has exactly one kind in its definition, you can't mix multiple entity types (Donation with Product in your case).

If you need such queries you can duplicate the necessary info and fill it in when you update the product property. Also if/when the respective Product's properties change you may need to update all Donation entities referencing it.

A maybe acceptable middle ground would be to use the actual product property value (the key itself) to order the query - at least you'd have all the donations linked to the same product entity grouped together.

Upvotes: 1

Related Questions