简体   繁体   English

检查 DB (Django) 中是否存在对象

[英]Checking that an object exists in DB (Django)

Consider this Django code:考虑这个 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)

What if the user was deleted from the DB before the transaction starts?如果在事务开始之前用户被从数据库中删除了怎么办? It would add an nonexistent user to group.users .它将向group.users添加一个不存在的用户。 This is an error.这是一个错误。

What to do in this situation to preserve DB integrity?在这种情况下该怎么做才能保持数据库的完整性?

If a user does not exist while adding into groups then the query will fail in database raising IntegrityError with message as follows:如果添加到组中时用户不存在,则查询将在数据库中失败并引发 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".

You would just add the get in the transaction.atomic block:您只需在transaction.atomic块中添加 get:

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

You can use exceptions to handle it as well:您也可以使用异常来处理它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM