user579619
user579619

Reputation: 165

Query Many to Many in Datastore with Filter

I have to 2 entity models

class User(ndb.Model):
    username = ndb.StringProperty()
    # other properties

class Item(ndb.Model):
    type = ndb.StringProperty()
    # other properties

with a many to many relationship between User and Item

class UserItem(ndb.Model):
    user = ndb.KeyProperty(kind=User)
    item = ndb.KeyProperty(kind=Item)
    # other properties

How can I query UserItem with a filter to Item.type. Something like select * from UserItem where UserItem.user = user_key and UserItem.item.type = item_type.

I know I can do it with StructuredProperty but there is an entity limit of 1mb. If it's not possible with the model how should I model the relationship to get get the query with filter work in datastore?

Thanks

Upvotes: 1

Views: 187

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

You can't do this, and you shouldn't try. The datastore is not a relational database, and shouldn't be used as one.

Rather than having a linking UserItem table, you should consider storing a list of keys in one of the entities. For example, you could add a field to User:

items = ndb.KeyProperty(kind=Item, repeated=True)

and then with your User object, get the items by key and filter out the ones you need:

user_items = ndb.get_multi(my_user.items)
relevant_items = [item for item in user_items if item.type == my_type]

The exact structure is going to depend on your use-case, but the point is not to think in terms of traditional relationships like you would in SQL.

Upvotes: 2

Related Questions