Hello,

I have a question about transactions and thread safe applications.

I have an invoice app, where I have a model like this:

class Counter(models.Model):
   client = models.ForeignKey(Client)
   number = models.CharField(max_length=10, db_index=True)
   class Meta:
        unique_together = (("client", "number"),)

Where number is the number of the invoice: "2010/321"

What I need is to create a view that takes the last invoice number of
a client, parse it and add 1. ie: "2010/321" -> "2010/322"

I have something like this:

@transaction.commit_on_success
def increment_counter(name, client):
    counter = Counter.objects.filter(client=client).order_by('-id')[0]
    #Step 2: Parse format and Increment the counter
    ....
    newcounter = "2010/322"
    counter.count = newcounter
    #Step 3: Save the new counter
    counter.save()


I don't know if this is the best approach.

Imagine that when the first thread (thread1) is in step2, the second
thread (thread2) just inserted a new value in the database, so the
counter is already on "2010/322" but thread1 will try to write the
same value. It will fail because there is already a row with that
value in the ddbb.

How can I solve this problem? Can I use the F() function for this?
Should I use SQL "SELECT ... FOR UPDATE" ?

Thank you very much,

Adrian Ribao

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to