在app引擎中过滤实体的子查询(python)

时间:2011-06-10 02:44:32

标签: python google-app-engine google-cloud-datastore

我有一个问题模型和一个响应模型,父母被设置为这样的特定问题:

class Question(db.Model):
  myQuestion = db.StringProperty()

class Response(db.Model):
  responder = db.ReferenceProperty(reference_class = User, collection_name = 'my_responses')
  myResponse = db.StringProperty()

def createQuestion(self, user, question):
  Question(myQuestion = question, parent = user).put()

def respond(self, user, question, response):
  Response(responder = user, myResponse = response, parent = question).put()

鉴于用户如何获得用户未回复的所有问题?

2 个答案:

答案 0 :(得分:1)

一种解决方案是保留用户已回复的问题列表。您可以将这些列表保留在用户的实体组中,并使用当前月份(例如)作为键名。

class QuestionsAnswered(db.Model):
    answered = db.ListProperty(db.Key)

将QuestionsAnswered实体的键名设置为当前月份(我喜欢'201106',对于instnace),并将它们放在用户的实体组中。这样可以轻松获取所需的列表。

要获取看不见的问题列表,您可以执行以下操作:

question_query = Questions.all().order('asked_date')
questions = questions.fetch(50)

if not questions:
  # return ... nothing to do here

month = questions[0].asked_date.strftime('%Y%m')
answered_list = QuestionsAnswered.get_by_key_name(month, parent=user)

question_keys = [question.key() for question in questions]
new_question_keys = set(question_keys) - set(answered_list.answered)

您可以对此进行扩展,以检查返回问题中最早的月份。如果没有返回足够的问题,您也可以将其扩展为再次获取。

答案 1 :(得分:1)

正如Robert Kluin建议的那样,你应该考虑添加一个“回应”字样。属性问题实体。你仍然可以像这样实现同样的目标。但这对你的问题来说是一个讨厌的解决方案

questions=Question.all().ancestor(user)
result = []
for question in questions:
    responded = Response.all().ancestor(question).get()
    if responded is not None:
       result.append(responded)