简体   繁体   中英

Many to many relationship with NDB on Google App Engine

I've got the following models...

class User(ndb.Model):
    email = ndb.StringProperty()
    username = ndb.StringProperty(indexed=True)
    password = ndb.StringProperty()

class Rel(ndb.Model):
    user = ndb.KeyProperty(kind=User, indexed=True)
    follows = ndb.KeyProperty(kind=User, indexed=True)
    blocks = ndb.KeyProperty(kind=User)

I'm trying to make it so a user can follow or block any other number of users.

Using the above setup I'm finding it hard to perform tasks that would been easy with a traditional DBMS.

As a simple example, how would I find all of a given user's followers AND order by username-- keeping in mind when I perform a query on Rel, I'm getting back keys and not user objects?

Am I going about this the wrong way?

You have to do a fetch but you can go about designing it in a better way,

the follows and blocks fields can be lists instead of just key -

follows = ndb.KeyProperty(kind=User, repeated=True)
blocks = ndb.KeyProperty(kind=User, repeated=True)

after this when you need the follows of this user you can get the keys and do an ndb.get_multi(Keys_list) to get all the follows/blocks entities whatever you need.

OR

A better way of doing this -

If you care about the order and want to paginate, you will have to store all the follow/block entities separately, for example if this is about a user 'a'

Follows entity will have records for each person 'a' follows

class FollowEntity(ndb.Model):
    user = ndb.KeyProperty(kind=User)
    follow = ndb.KeyProperty(kind=User)
    follow_username = ndb.StringProperty()

a query can be assuming user is an entry from your 'User' Entity.

query = FollowEntity.query(FollowEntity.user == user.key).order(FollowEntity.follow_username)

you can run this query and get the sorted username results, would work well if you use fetch_page to display the results in a batch.

Do the same for BlockEntity too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM