google app engine - NDB Modeling One-to-one with KeyProperty -
i'm quite new ndb i've understood need rewire area in brain create models. i'm trying create simple model - sake of understanding how design ndb database - one-to-one relationship: instance, user , info. after searching around lot - found documentation hard find different examples - , experimenting bit (modeling , querying in couple of different ways), solution found:
from google.appengine.ext import ndb class monster(ndb.model): name = ndb.stringproperty() @classmethod def get_by_name(cls, name): return cls.query(cls.name == name).get() def get_info(self): return info.query(info.monster == self.key).get() class info(ndb.model): monster = ndb.keyproperty(kind='monster') address = ndb.stringproperty() = monster(name = "dracula") a.put() b = info(monster = a.key, address = "transilvania") b.put() print monster.get_by_name("dracula").get_info().address
ndb doesn't accept joins, "join" want has emulated using class methods , properties. above system can reach property in second database (info) through unique property in first (in case "name" - suppose there no 2 monsters same name).
however, if want print list 100 monster names , respective addresses, second database (info) hit 100 times.
question: there better way model increase performance?
if 1 one relationship, why creating 2 models. given example address entity cannot shared monster why not put address details in monster.
there reasons why wouldn't.
address become large , therefore less efficient retrieve 100's of properties when need couple - though project queries may there.
you change mind , want see monsters live in transylvania - in case create address entity , monster have key property points address. fails when work out monsters can live in multiple places (werewolfs - london, transylvania, new york ;-) , in case either have repeating keyproperty in monstor or intermediate entity points monster , address. in case don't think monsters on whole have many documented addresses ;-)
also if uniquely identifying monsters name should consider storing name part of key. doing monster.get_by_id("dracula") quicker query name.
as wrote (poorly) in comment. if 1. above holds , true 1 one relationship. create address child entity (monster parent/ancestor in key) when creating address. allows to,
- allow other entities point address,
- if create bunch of child entities, fetch them single ancestor query). 3 if have monster , it's owned entities again it's ancestor query.
- if have bunch of entities should exist if monster instance exists , not children, have querys on entity types keyproperty's matching key, , if theses entities not polymodels, have perform query each entity type (and know need perform query on given entity, involves registry of type, or hard coding things)
Comments
Post a Comment