Kris
Kris

Reputation: 10307

Relationships in the Datastore (One-to-Many)

I was actually just wondering what the most efficient way to model a relationship of this kind would be in the google datastore.

Say I have 'Users' and 'Projects'. A project may have many users (One-to-Many). Is there a better way over modelling it like this?

class Users(ndb.Model):
    properties...

class Projects(ndb.Model):
    properties...

class UserToProject(ndb.Model):
    user = ndb.KeyProperty(Users)
    project = ndb.KeyProperty(Projects)

I'm looking at this from a 'normalization' standpoint, but I'm guessing there's probably a less costly way...

Upvotes: 2

Views: 682

Answers (1)

ChrisC73
ChrisC73

Reputation: 1863

What you have here is a many-to-many relationship as a project has many users and a user may be assigned to many projects (I assume).

Using NDB we can try to forget about traditional database relationships and focus on the objects themselves. The simplest way to represent this is to link a list of projects to a user:

class Project(ndb.Model):
    properties...

class User(ndb.Model):
    properties...
    projectKeys = Ndb.KeyProperty(kind=Project, repeated=True)

Now, when viewed from a user's perspective, we can simply retrieve all projects they belong to:

user = User.query(...).get()
projectKeys = user.projectKeys # you can retrieve these as required

When viewed from a project viewpoint, you can find linked users as follows:

project = Project.query(...).get()
users = User.query(User.projectKeys=project.key).fetch()

Caveat: Friday afternoon - untested code. Concepts should hopefully help though :)

Upvotes: 2

Related Questions