Christian
Christian

Reputation: 1166

I can't assign a parent to a child in Google App Engine's Datastore. What am I doing wrong?

In the code below, I'm inserting one piece of data, and then a second one assigning the first as the parent. Both pieces of data go in, but no parent relationship is created. What am I doing wrong?

from google.appengine.ext import db

class Test_Model(db.Model):
  """Just a model for testing."""
  name = db.StringProperty()

# Create parent data
test_data_1 = Test_Model()
test_data_1.name = "Test Data 1"
put_result_1 = test_data_1.put()

# Create child data
test_data_2 = Test_Model()
test_data_2.name = "Test Data 2"
# Here's where I assign the parent to the child
test_data_2.parent = put_result_1
put_result = test_data_2.put()

query = Test_Model.all()

results = query.fetch(100)
for result in results:
  print "Name: " + result.name
  print result.parent()

Upvotes: 3

Views: 146

Answers (2)

Christian
Christian

Reputation: 1166

I realize my misunderstanding now. You have to set the parent at the time of creation like so:

test_data_2 = Test_Model(parent = put_result_1)

Here's the full fixed code sample for posterity.

from google.appengine.ext import db

class Test_Model(db.Model):
  """Just a model for testing."""
  name = db.StringProperty()

# Create parent data
test_data_1 = Test_Model()
test_data_1.name = "Test Data 1"
put_result_1 = test_data_1.put()

# Create child data
test_data_2 = Test_Model(parent = put_result_1)
test_data_2.name = "Test Data 2"
put_result = test_data_2.put()

query = Test_Model.all()

#query.filter('name =', 'Test Data 1')
#query.ancestor(entity)

results = query.fetch(1000)
for result in results:
  print "Name: " + result.name
  print result.parent()

Upvotes: 2

Aaron Digulla
Aaron Digulla

Reputation: 328790

Where in your model do you define the field parent? You define only name.

Therefore GAE ignores the unknown parent field.

Upvotes: 0

Related Questions