I have a table with a foreign key. (I deliberately use foreign key here and not one-to-one).
I have an Order model:
class Order:
name = models.CharField(max_length=50)
user = models.ForeignKey(User)
active = models.BooleanField(default=True)
# more fields..
And I want that only one instance of this model will exist per user.
I have a simple form (and view) that saves it. And I have this code:
try:
instance = Order.objects.get(user=user)
except Order.DoesNotExist:
instance = None
form = OrderForm(instance=instance)
But I noticed that if the client fire two consequent request at the same time (noticed that as I use ajax), then two instances might get created, despite my the following validation (which suppose to update the existing one).
This is very important as my other code expect only one instance of this model per user. How can I enforce that in django? I've tried the following on my view:
@method_decorator(transaction.atomic, name='dispatch')
But didn't work. And as I've said, I can't use One-to-one field here.
You may enforce unicity at the database level with unique_together
and a nullable field:
class Order:
name = models.CharField(max_length=50)
user = models.ForeignKey(User)
active = models.NullBooleanField(default=True)
class Meta:
unique_together = (('user', 'active'), )
The trick is to set active
to None
instead of False
for inactive orders. As NULL
values are not considered equal at the database level, a user may have multiple inactive orders but only one active one.