I have a model Entry
class Entry(db.Model):
year = db.StringProperty()
.
.
.
and for whatever reason the last name field is stored in a different model LastName:
class LastName(db.Model):
entry = db.ReferenceProperty(Entry, collection_name='last_names')
last_name = db.StringProperty()
If I query Entry and sort it by year (or any other property) using .order() how would I then sort that by the last name? I’m new to python but coming from Java I would guess there’s some kind of comparator equivalent; or I’m completely wrong and there’s another way to do it. I for sure cannot change my model at this point in time, though that may be the solution later. Any suggestions?
EDIT: I’m currently paginating through the results using offsets (moving to cursors soon, but I think it would be the same issue). So if I try to sort outside of the datastore I would only be sorting the current set; it’s possible that the first page will be all ‘B’s and the second page will have ‘A’s, so it will only be sorted by page not by overall set. Am I screwed the way my models are currently set up?
A few issues here.
There’s no way to do this sorting directly in the datastore API, either in Python or Java – as you no doubt know, the datastore is non-relational, and indirect lookups like this aren’t supported.
If this was just a straight one-to-one relationship, which gave you an accessor from the
Entryentity to theLastNameone, you could use the standard Pythonsortfunction to sort the list:(note that this sorts the list in place but returns None, so don’t try assigning from it).
However, this won’t work, because what you’ve actually got here is a one-to-many relationship: there are potentially many LastNames for each Entry. The definition actually recognises this: the
collection_nameattribute, which defines the accessor from Entry to LastName, is calledlast_names, ie plural.So what you’re asking doesn’t really make sense: which of the potentially many LastNames do you want to sort on? You can certainly do it the other way round – given a query of LastNames, sort by entry year – but given your current structure there’s not really any way of doing it.
I must say though, although I don’t know the rest of your models, I suspect you have actually got that relationship the wrong way round: the
ReferencePropertyshould probably live onEntrypointing toLastNamerather than the other way round as it is now. Then it would simply be the sort call I gave above.