I cannot assign a parent to a child in the Google App Engine datastore. What am I doing wrong?

In the code below, I insert one piece of data and then the second, assigning the first as the parent. Both pieces of data are included, but parent relationships are not 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 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()
+3
source share
2 answers

Now I understand my misunderstanding. You must set the parent at creation time like this:

test_data_2 = Test_Model(parent = put_result_1)

Here's a complete sample of fixed code 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()
+2
source

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

Therefore, GAE ignores an unknown field parent.

0
source

Source: https://habr.com/ru/post/1714874/


All Articles