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?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With