简体   繁体   中英

Checking that an object exists in DB (Django)

Consider this Django code:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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