Django: Avoiding ABA scenario in Database and ORM’s

I have a situation where I need to update votes for a candidate.

Citizens can vote for this candidate, with more than one vote per candidate. i.e. one person can vote 5 votes, while another person votes 2. In this case this candidate should get 7 votes.

Now, I use Django. And here how the pseudo code looks like

votes = candidate.votes 
vote += citizen.vote 

The problem here, as you can see is a race condition where the candidate’s votes can get overwritten by another citizen’s vote who did a select earlier and set now.

How can avoid this with an ORM like Django?

Answers


If this is purely an arithmetic expression then Django has a nice API called F expressions


Updating attributes based on existing fields

Sometimes you'll need to perform a simple arithmetic task on a field, such as incrementing or decrementing the current value. The obvious way to achieve this is to do something like:

>>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
>>> product.number_sold += 1
>>> product.save()

If the old number_sold value retrieved from the database was 10, then the value of 11 will be written back to the database.

This can be optimized slightly by expressing the update relative to the original field value, rather than as an explicit assignment of a new value. Django provides F() expressions as a way of performing this kind of relative update. Using F() expressions, the previous example would be expressed as:

>>> from django.db.models import F
>>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
>>> product.number_sold = F('number_sold') + 1
>>> product.save()

This approach doesn't use the initial value from the database. Instead, it makes the database do the update based on whatever value is current at the time that the save() is executed.

Once the object has been saved, you must reload the object in order to access the actual value that was applied to the updated field:

>>> product = Products.objects.get(pk=product.pk)
>>> print product.number_sold
42

Need Your Help

How to work with Database over SOAP in Django?

python django soap django-models suds

Currently I have a Django project, let's call it Backend. There is a folder api and there I have this resource declared using Django-Tastypie:

Using jQuery Mobile, onclick not triggering with PhoneGap on Android

javascript jquery cordova jquery-mobile jquery-validate

I'm using jquery.validate.js with a multipage jquery mobile app. I'm using onclick= to validate each page/form before moving on to the next page. This works correctly in iOS and Android when access...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.