考虑这个Django代码:
class User(models.Model):
name = models.CharField(null=True, blank=False, verbose_name=_("Name"), help_text='User Name', max_length=256)
class UsersGroup(models.Model):
name = models.CharField(null=False, blank=False, verbose_name=_("Name"), help_text='Users Group Name', max_length=256)
users = models.ManyToManyField(User)
# ...
with transaction.atomic():
group.users.add(user)
如果用户在事务开始之前从数据库中删除了怎么办?它会向group.users
添加一个不存在的用户。这是一个错误。
在这种情况下如何处理以保持数据库完整性?
答案 0 :(得分:1)
如果在添加到组中时用户不存在,那么查询将在数据库引发IntegrityError时失败,并显示以下消息:
IntegrityError: insert or update on table "app1_usersgroup_users" violates foreign key constraint "app1_usersgroup_users_user_id_96d48fc7_fk_polls_user_id"
DETAIL: Key (user_id)=(3) is not present in table "polls_user".
答案 1 :(得分:0)
您只需在transaction.atomic
块中添加get:
with transaction.atomic():
user = User.objects.get(name='stackoverflow')
group.users.add(user)
答案 2 :(得分:0)
您也可以使用例外来处理它:
try:
group.users.add(User.objects.get(name='Julian'))
except:
# handle the error - user doesn't exist