Reputation: 105
@property
def returns_an_int(self):
some_var = do_something_that_returns_int()
if some_var:
return int(some_var)
else:
return 0
I have a property using the code above, which is supposed to (and does) return an int. (I put the int casting on it to double check) However when I try to use it to order a fetch,cls.query().order(cls.returns_an_int)
I get a type error TypeError: order() expects a Property or query Order; received <property object at 0xsome-hex-address>
- I have tried using + or - to see if I can make it get a value because I saw it in other questions but it didn't work. What am I doing wrong? Am I missing something basic to make it work?
Upvotes: 0
Views: 111
Reputation: 309949
When you query the datastore, you need to query on one of the various ndb.Property
types. You are querying on a vanilla python property. This doesn't work because the python property data never gets stored in the datastore and so the datastore can't order by data that it doesn't know about.
It's hard to give definitive advice on how to fix this. You can do your query without the .order
and sort in client code:
return sorted(cls.query(), key=lambda item: item.returns_an_int)
but that won't work for entity types that have lots of entities. You could also change your property to an ndb.ComputedProperty
:
@ndb.ComputedProperty
def returns_an_int(self):
some_var = do_something_that_returns_int()
if some_var:
return int(some_var)
else:
return 0
The downside here is that you're storing (and paying for) more datastore data and you also execute the returns_an_int
method for every datastore put. If it is a fast method to execute, that shouldn't be a problem, but if it is a slow method you might start to notice the difference.
Upvotes: 3