具有2个字段的简单数据存储区实体也是唯一的

时间:2013-12-18 17:55:17

标签: google-app-engine google-cloud-datastore

我尝试制作的所有内容都是一个拥有唯一用户名和唯一设备ID的实体,并且如果在提交时未满足其中任何一个条件,则能够返回错误。

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

这样做的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

这是一个做你想要的例子。

我放了2个实体来向你展示如何建立关系

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

还要回答评论问题:

  

如何以编程方式判断返回的实体是否为新实体   或现有的?

尝试检查默认属性。例如creation_date等。 虽然你也可以检查你需要的东西,或者像我一样检查另一个实体的存在,因为我希望数据是一致的,如果没有,那就创建一个债券。