probably at the beach
probably at the beach

Reputation: 15207

python app engine Model query for models in the same group

I have transactional Groups of entities of type db.Model that have a parent defined. I want to query the datastore to only return models that are in the same group. Currently I'm querying all objects of a 'Kind' then removing those that don't have the same root entity.

Is there a cleaner way to do this - I can't see one in the sdk.

for example:

from google.appengine.ext import db

class ParentObject(db.Model):
  ....


class ChildObject(db.Model):
  ....


parent1 = ParentObject()
parent2 = ParentObject()
child1 = ChildObject(parent=parent1)
child2 = ChildObject(parent=parent2)
child3 = ChildObject(parent=parent1)

I want to run a query that returns child1 and child3 because they have the same parent.

Upvotes: 3

Views: 145

Answers (2)

Abdul Kader
Abdul Kader

Reputation: 5842

I think this is what you are looking for.

get_chlids=ChildObject.all().ancestor(parent1)

To know more about modeling in appengine. You can have a look here

Upvotes: 3

probably at the beach
probably at the beach

Reputation: 15207

class TestFamilyTree(unittest.TestCase):

def test_family_tree(self):
  parent1 = ParentObject()
  parent1.put()
  parent2 = ParentObject()
  parent2.put()
  child1 = ChildObject(parent=parent1)
  child1.put()
  child2 = ChildObject(parent=parent2)
  child2.put()
  child3 = ChildObject(parent=parent1)
  child3.put()
  query = ChildObject.all()
  query.ancestor(child1.parent())
  siblings = query.fetch(100)
  self.assertEqual(len(siblings),2) 

Upvotes: 1

Related Questions