nextdoordoc
nextdoordoc

Reputation: 1767

Django : after saving model how not allow model to be updated anymore?

I have reservation model like below.

class Reservation(models.Model):
    user = models.ForeignKey('index:User', null=True)
    shop = models.ForeignKey('index:Shop')
    datetime = models.DateTimeField(null=True, error_messages={})

And customers who use website can reserve and if they click reserve button form submission happen. View is described below.

...
if form.is_valid:
    user = request.user

    # check if reservation happend before by other customer
    if reservation.user == None:
        # if reservation user attribute is empty. allocate user attribute.
        reservation.user = user
        reservation.save()

But Let's guess two people, A and B are trying to reserve the same reservation object. A first click and check reservation.user is None and trying to allocate user attribute to reservation object while B check that reservation.user is None.

In this situation B can override reservation.user attribute. But I don't want this override happen.. and also let B to know that reservation is already finished. How can I make it?

Thanks in advance

Upvotes: 1

Views: 323

Answers (1)

cdvv7788
cdvv7788

Reputation: 2099

After looking around for a while the best option i found seems to be django-concurrency.

It implements optimistic locks that as i understood (new to this xD) does not lock the object and forces the other threads to wait. Instead it goes on and completes the operation but before saving to the database checks that the object has not been modified since it was read and then saves it.

They give and example that is pretty much like what you want:

a = ConcurrentModel.objects.get(pk=1)
b = ConcurrentModel.objects.get(pk=1)
a.save()
b.save()

Checking the commits it seems it is ready for django 1.7 but the documentation has not been updated completely yet.

To make this works seems to be simple...just add one of the concurrency.fields.VersionField to the models that need this feature.

I have not tested this personally as i haven't need this so far (but i can see some cases where i may...thanks). Test it and if something does not work leave a comment.

Upvotes: 1

Related Questions