How to think in data stores instead of databases?

前端 未结 8 2327
滥情空心
滥情空心 2020-11-28 17:32

As an example, Google App Engine uses Google Datastore, not a standard database, to store data. Does anybody have any tips for using Google Datastore instead of databases?

8条回答
  •  情话喂你
    2020-11-28 17:50

    I always chuckle when people come out with - it's not relational. I've written cellectr in django and here's a snippet of my model below. As you'll see, I have leagues that are managed or coached by users. I can from a league get all the managers, or from a given user I can return the league she coaches or managers.

    Just because there's no specific foreign key support doesn't mean you can't have a database model with relationships.

    My two pence.


    class League(BaseModel):
        name = db.StringProperty()    
        managers = db.ListProperty(db.Key) #all the users who can view/edit this league
        coaches = db.ListProperty(db.Key) #all the users who are able to view this league
    
        def get_managers(self):
            # This returns the models themselves, not just the keys that are stored in teams
            return UserPrefs.get(self.managers)
    
        def get_coaches(self):
            # This returns the models themselves, not just the keys that are stored in teams
            return UserPrefs.get(self.coaches)      
    
        def __str__(self):
            return self.name
    
        # Need to delete all the associated games, teams and players
        def delete(self):
            for player in self.leagues_players:
                player.delete()
            for game in self.leagues_games:
                game.delete()
            for team in self.leagues_teams:
                team.delete()            
            super(League, self).delete()
    
    class UserPrefs(db.Model):
        user = db.UserProperty()
        league_ref = db.ReferenceProperty(reference_class=League,
                                collection_name='users') #league the users are managing
    
        def __str__(self):
            return self.user.nickname
    
        # many-to-many relationship, a user can coach many leagues, a league can be
        # coached by many users
        @property
        def managing(self):
            return League.gql('WHERE managers = :1', self.key())
    
        @property
        def coaching(self):
            return League.gql('WHERE coaches = :1', self.key())
    
        # remove all references to me when I'm deleted
        def delete(self):
            for manager in self.managing:
                manager.managers.remove(self.key())
                manager.put()
            for coach in self.managing:
                coach.coaches.remove(self.key())
                coaches.put()            
            super(UserPrefs, self).delete()    
    

提交回复
热议问题