Many-to-many relationship in ndb

An attempt to model many-to-many relationships with ndb. Can anyone point out a good example of how to do this?

Here is an example of what I have at the moment:

class Person(ndb.Model): guilds = ndb.KeyProperty(kind="Guild", repeated=True) class Guild(ndb.Model) members = ndb.KeyProperty(kind="Person", repeated=True) def add_person(self, person): self.members.append(person.key) self.put() person.guilds.append(self.key) person.put() 

Is it correct? I looked around well, but I can not find good documentation on this.

In the data warehouse viewer, I see that this relation is stored as a list of keys that I expect.

However, when I try to use them in methods of the Person class, for example:

 for guild in self.guilds: 

I get:

 TypeError: 'KeyProperty' object is not iterable 
+8
python google-app-engine many-to-many app-engine-ndb
source share
1 answer

Not. This is not the right way.

You can model many-to-many relationships with just one repetitive property:

 class Person(ndb.Model): guilds = ndb.KeyProperty(kind="Guild", repeated=True) class Guild(ndb.Model): @property def members(self): return Person.query().filter(Person.guilds == self.key) def add_person(self, person): person.guilds.append(self.key) person.put() 

or vice versa:

 class Person(ndb.Model): @property def guilds(self): return Guild.query().filter(Guild.members == self.key) class Guild(ndb.Model): members = ndb.KeyProperty(kind="Person", repeated=True) def add_person(self, person): self.members.append(person.key) self.put() 

The direction of the relationship depends on many factors (your business model, number of guilds per person, number of members per guild, etc.)

+12
source share

All Articles