user47376
user47376

Reputation: 2273

python ndb classes that reference each other

I have two classes:

class A(ndb.Model):
    first_prop = ndb.StructuredProperty(B)

class B(ndb.Model):
    second_prop = ndb.StructuredProperty(A)

putting the class name in quotes gives an error.

What is a reasonable way to make it happen , which leaves code encapsulation intact ?

Upvotes: 0

Views: 187

Answers (2)

Dmytro Sadovnychyi
Dmytro Sadovnychyi

Reputation: 6201

You can assign a property after the models were defined. See _fix_up_properties doc strings here.

class A(ndb.Model):
  pass

class B(ndb.Model):
  pass

A.first_prop = ndb.StructuredProperty(B)
B.second_prop = ndb.StructuredProperty(A)
A._fix_up_properties()
B._fix_up_properties()

Upvotes: 2

minou
minou

Reputation: 16563

You probably want to use ndb.KeyProperty instead of ndb.StructuredProperty. Using the former, it is perfectly acceptable to have two classes reference each other.

Upvotes: 1

Related Questions