-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmodels.py
More file actions
25 lines (21 loc) · 962 Bytes
/
models.py
File metadata and controls
25 lines (21 loc) · 962 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from django.db import models, transaction
from django.conf import settings
# Create your models here.
class BroadcastMessage(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='messages')
message = models.TextField()
active = models.BooleanField(default=True)
def save(self, *args, **kwargs):
if self.active:
# Use atomic transaction with row locking to prevent race conditions
with transaction.atomic():
# Lock and deactivate all user's active messages
BroadcastMessage.objects.select_for_update().filter(
user=self.user, active=True
).update(active=False)
# Save this message as active
super().save(*args, **kwargs)
else:
super().save(*args, **kwargs)
def __str__(self):
return f'{self.user.username}: {self.message[:20]}'