Google app engine 简单数据存储实体,包含两个字段,且字段也是唯一的

Google app engine 简单数据存储实体,包含两个字段,且字段也是唯一的,google-app-engine,google-cloud-datastore,Google App Engine,Google Cloud Datastore,我所要做的就是创建一个实体,它拥有唯一的用户名和唯一的设备ID,并且能够在提交时不满足这些条件时返回错误 我能看到的唯一方法是在事务中执行查询,然后过滤结果。然而,这需要一个祖先(对于单个简单实体来说,这似乎是不必要的) 做这件事的最佳方法是什么?这里有一个例子,可以满足您的需要 我放置了两个实体来向您展示如何建立关系 class Person(ndb.Expando): registration_date = ndb.DateTimeProperty(auto_now_add=Tru

我所要做的就是创建一个实体,它拥有唯一的用户名和唯一的设备ID,并且能够在提交时不满足这些条件时返回错误

我能看到的唯一方法是在事务中执行查询,然后过滤结果。然而,这需要一个祖先(对于单个简单实体来说,这似乎是不必要的)


做这件事的最佳方法是什么?

这里有一个例子,可以满足您的需要

我放置了两个实体来向您展示如何建立关系

class Person(ndb.Expando):

    registration_date = ndb.DateTimeProperty(auto_now_add=True)

    @property
    def info(self):
        info = PersonInfo.query(ancestor=self.key).get()
        return info

class PersonInfo(ndb.Expando):

    email = ndb.StringProperty()
    nick_name = ndb.StringProperty()
    edit_date = ndb.DateTimeProperty(auto_now=True)
稍后在控制器的寄存器中:

class RegisterPersonHandler(webapp2.RequestHandler):

    def get(self):
        user = users.get_current_user() #Stub here 
        if not user:
            self.redirect(users.create_login_url(self.request.uri), abort=True)
            return
        person = Person.get_or_insert(user.user_id())
        if not self._register(person, user):
            # more logging is needed
            logging.warning('Warning registration failed')
            return


    @ndb.transactional()
    def _register(self, person, user):
        ''' Registration process happens here
        '''
        # check if the person has info and if not create it
        info = PersonInfo.query(ancestor=person.key).get()
        if not info:
            info = PersonInfo(id=user.user_id(), parent=person.key)
            info.nick_name = user.nickname()
            info.email = user.email()
            info.put()
        return True
要回答评论问题,请执行以下操作:


如何通过编程判断返回的实体是否为新实体 还是现有的

尝试检查默认属性。例如创建日期等。
尽管你也可以像我一样检查你需要的东西或另一个实体的存在,因为我希望数据是一致的,如果不一致,那么就创建绑定。

使用get\u或\u insert。它可以使用父实体键(如果有)。但是,如何通过编程判断返回的实体是新实体还是现有实体?谢谢,就这样。