维护 NDB 数据库中属性的唯一性 [英] Maintain uniqueness of a property in the NDB database

查看:19
本文介绍了维护 NDB 数据库中属性的唯一性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个 NDB 模型包含两个属性:emailpassword.如何避免将具有相同email 的两条记录添加到数据库中?NDB 没有像关系数据库那样的属性的 UNIQUE 选项.

An NDB model contains two properties: email and password. How to avoid adding to the database two records with the same email? NDB doesn't have UNIQUE option for a property, like relational databases do.

在添加之前检查新的email不在数据库中——我不会满足,因为两个并行进程可以同时进行检查并且每个进程都添加相同的email.

Checking that new email is not in the database before adding—won't satisfy me, because two parallel processes can both simultaneously do the checking and each add the same email.

我不确定事务在这里是否有帮助,我在阅读了一些手册后就有了这种印象.也许是同步事务?一次一个吗?

I'm not sure that transactions can help here, I am under this impression after reading some of the manuals. Maybe the synchronous transactions? Does it mean one at a time?

推荐答案

通过邮件创建实体的key,然后使用get_or_insert 检查是否存在.

Create the key of the entity by email, then use get_or_insert to check if exists.

另请阅读有关键、实体的信息.模型

#ADD
key_a = ndb.Key(Person, email);
person = Person(key=key_a)
person.put()

#Insert unique    
a = Person.get_or_insert(email)

或者如果您只想检查

#ADD
key_a = ndb.Key(Person, email);
person = Person(key=key_a)
person.put()

#Check if it's added
new_key_a =ndb.Key(Person, email);
a = new_key_a.get()
if a is not None:
    return

保重.更改电子邮件将非常困难(需要创建新条目并将所有条目复制到新的父项).

Take care. Changing email will be really difficult (need to create new entry and copy all entries to new parent).

为此,您可能需要将电子邮件存储在另一个实体中,并使用户成为其父实体.

For that thing maybe you need to store the email, in another entity and have the User be the parent of that.

另一种方法是使用交易并检查电子邮件属性.事务的工作方式:首先提交的是第一个获胜.一个概念意味着如果 2 个用户检查电子邮件,则只有第一个(幸运的)用户会成功,因此您的数据将保持一致.

Another way is to use Transactions and check the email property. Transaction's work in the way: First that commits is the First that wins. A concept which means that if 2 users check for email only the first (lucky) one will succeed, thus your data will be consistent.

这篇关于维护 NDB 数据库中属性的唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆