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

查看:96
本文介绍了在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?

推荐答案

通过电子邮件创建实体的密钥,然后使用

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).

为此,您可能需要将电子邮件存储在另一个实体中,并让User作为该电子邮件的父代.

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天全站免登陆