How do you treat a ReferenceProperty like a boolean in AppEngine Datastore?

大憨熊 提交于 2019-12-13 04:20:04

问题


I have a model which might reference another model and which has a completed_on date.

class Game(db.Model):
    challenge = db.ReferenceProperty(Challenge, required=False)
    completed_on = db.DateTimeProperty(default=None)

I'd like to be able to select all of the completed Challenge games that were completed before a certain time period. Problem is I can't have 2 inequalities

But http://code.google.com/appengine/docs/python/datastore/queries.html says:

Inequality Filters Are Allowed on One Property Only:

Which means I can't do challenge > '' and completed_on < datetime_value

However I could do is_challenge=True and completed_on < datetime_value provided I add a new column to the db called is_challenge. With that in mind, is there someway to convince the datastore to treat challenge as a boolean?

It appears it can't be done this way, and I'm hoping there is some other way to accomplish this without having to add yet another column to the model and probably yet another index to go with that column.

I am expecting the list of games to be large enough to not want to filter it in python for every page displayed.


回答1:


The only way to do this is, as you observe, to add a boolean property that indicates if challenge is set or not. You can do this with ease by using ComputedProperty:

class Game(db.Model):
    challenge = db.ReferenceProperty(Challenge, required=False)
    completed_on = db.DateTimeProperty(default=None)

    @db.ComputedProperty
    def has_challenge(self):
      return self.challenge is not None


来源:https://stackoverflow.com/questions/7541059/how-do-you-treat-a-referenceproperty-like-a-boolean-in-appengine-datastore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!