Checking that an object exists in DB (Django)
<p>Consider this Django code:</p>

<pre><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)
</code></pre>

<p>What if the user was deleted from the DB before the transaction starts? It would add an nonexistent user to <code>group.users</code>. This is an error.</p>

<p>What to do in this situation to preserve DB integrity?</p>

<p>You would just add the get in the <code>transaction.atomic</code> block:</p>

<pre><code>with transaction.atomic():
    user = User.objects.get(name='stackoverflow')
    group.users.add(user)
</code></pre>

python django transactions referential-integrity