Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a synchronized way to validate models in Django?

Tags:

python

django

I have a Django model called TimeSpan with a start_datetime and end_datetime field, and I want to do validation on the model so that no two TimeSpan objects overlap.

However, if I wrote code like below,

if timespan.is_valid():
    timespan.save()

then there could be a race condition where two TimeSpan objects are deemed valid compared to what is currently in the database, and then they are both saved despite being invalid together.

I could make a synchronized validate_and_save() method with locks, but that would break the Django admin. Is there an alternative built into Django?

like image 871
HatTricks Avatar asked Nov 11 '22 03:11

HatTricks


1 Answers

You need to use transactions if you head down this direction, however I would suggest that you look at your database's trigger functionality instead...

like image 188
thebjorn Avatar answered Nov 15 '22 07:11

thebjorn