检查数据库中是否存在对象(Django)

Checking that an object exists in DB (Django)

考虑这个 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。这是一个错误。

在这种情况下如何做才能保持数据库的完整性?

您只需在 transaction.atomic 块中添加 get:

with transaction.atomic():
    user = User.objects.get(name='Whosebug')
    group.users.add(user)

你也可以使用异常来处理:

    try:
      group.users.add(User.objects.get(name='Julian'))
    except:
      # handle the error - user doesn't exist

如果在添加到组时用户不存在,则查询将在数据库中失败并引发 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".