porton porton - 1 year ago 55
Python Question

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():

What if the user was deleted from the DB before the transaction starts? It would add an nonexistent user to
. This is an error.

What to do in this situation to preserve DB integrity?

Answer Source

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