我有两个在数据库中创建记录的场景。假设我正在使用foo@bar.com
.
- 场景 1:假设我有一个电子邮件用户
foo@bar.com
- 场景 2:假设我有一个使用电子邮件的用户
foo@bar.com
方案 2引发了一个错误,指出已经存在foo@bar.com
. 我认为我需要设置一个挂钩来清理场景之间的数据库。
这种情况的最佳做法是什么?flushdb
在场景之间调用命令?还是事务回滚?或者还有什么?
我有两个在数据库中创建记录的场景。假设我正在使用foo@bar.com
.
foo@bar.com
foo@bar.com
方案 2引发了一个错误,指出已经存在foo@bar.com
. 我认为我需要设置一个挂钩来清理场景之间的数据库。
这种情况的最佳做法是什么?flushdb
在场景之间调用命令?还是事务回滚?或者还有什么?
在这两种情况下都使用该get_or_create
方法。不要忘记get_or_create
返回一个元组:
>>> from django.contrib.auth.models import User
>>> superman, created = User.objects.get_or_create(username='kal-el')
>>> superman
<User: kal-el>
>>> created
True
>>> superman_returns, created_again = User.objects.get_or_create(username='kal-el')
>>> superman_returns
<User: kal-el>
>>> created_again
False
https://docs.djangoproject.com/en/1.8/ref/models/querysets/#get-or-create