Note that there are some explanatory texts on larger screens.

plurals
  1. POAtomic database operations in Django 1.4
    text
    copied!<p>This question is similar to <a href="https://stackoverflow.com/questions/280075/atomic-operations-in-django">Atomic operations in Django?</a> however for Django 1.4. I'm wondering if there is a way to do this <em>without</em> resorting to "raw SQL". My setup is a little different then his so I'll explain.</p> <p>I have a record for a <em>User</em> and a generic table called <em>UserRecords</em>. Here's the definition for <em>UserRecord</em>.</p> <pre><code>class UserRecord (models.Model): """ User record model for :class:`User` users to keep aux data like services connected, latest stats, and other accounts. """ def __unicode__ (self): return u"{0}.{1}.{2}.{3}".format(self.user, self.parent, self.key, self.value) def update_maybe_save (self, val): if self.value != val: self.value = val self.save() #: :class`User` who owns this record user = models.ForeignKey("User") parent = models.CharField(max_length=255, blank=True, null=True, db_index=True) key = models.CharField(max_length=255, db_index=True) value = models.TextField(blank=True, null=True) </code></pre> <p>As you can see, it's a very generic k/v store table with the optional <em>parent</em> attribute that's useful for grouping records together and optimizing some searches. It's very useful when, in this case, we want to add a couple alias's for a user.</p> <pre><code># Inside the User model def add_alias (self, name): try: UserRecord.objects.get(user=self, parent="alias", key=name, value=self.username) except UserRecord.DoesNotExist: UserRecord(user=self, parent="alias", key=name, value=self.username).save() </code></pre> <p>This sets ourselves up for a race condition where if a user enters the same alias twice it could create two identical records. Then each <code>UserRecord.objects.get</code> call fails because there are two, I get a Django error email, and I manually go fix the database. </p> <p>I can't find anything in the documentation that allows me to create something atomically. Any ideas apart from the raw sql mentioned in the other question?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload