1

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?

porton
  • 5,214
  • 11
  • 47
  • 95
  • @MosesKoledoye Users are added through a Web interface. I don't understand you: How is this related with the way users are added? – porton Sep 27 '16 at 17:05

3 Answers3

1

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".
0

You would just add the get in the transaction.atomic block:

with transaction.atomic():
    user = User.objects.get(name='stackoverflow')
    group.users.add(user)
2ps
  • 15,099
  • 2
  • 27
  • 47
0

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
galfisher
  • 1,122
  • 1
  • 13
  • 24