Search code examples
databasegoogle-app-enginegoogle-cloud-datastorenon-relational-database

Relating one model to multiple models based on field


Here's a brief description of the models:

  • Model A represents a piece of equipment and has a name and a state
  • Model B represents a specific state of many model A's
  • Model B should relate to many model A's but only for a specific state of model A

Is it possible to model something like this in the datastore? I need the state of model A to be independent of any model B's, but when I peer into a model B I need to know what the state of the model A's should be that the model B is representing.

The current way I am achieving this is by making model B have string fields representing the different model A's with the name of the field being the name of the model A and the value of the field being the state the model A is supposed to be in.

This works, however it's completely static and requires manually adding fields into model B when the number of model A's change. I'm looking for a dynamic approach to solve this problem.

I hope this isn't too confusing, please ask for more clarification if it's needed.


Solution

  • You can use reference properties for this:

    class A(db.Model):
        state = db.ReferenceProperty(collection_name="equipment")
    

    When you create A, you set the state property to the corresponding B entity.

    This also creates a property in the B entity called equipment that can be used to get all the A entities that reference the particular B.

    Suppose you have a B entity for broken equipment in a variable broken. You can get all the broken equipment this way

    broken.equipment.get()
    

    This is also available with ndb but the details are a little different and you'll need to check the docs for that.