[Fixed]-Django โ€“ make sure one related object is created, race condition

1๐Ÿ‘

โœ…

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.

๐Ÿ‘คaumo

0๐Ÿ‘

You can set unique=true for user. That will ensure only one order per user.

class Order:
  name = models.CharField(max_length=50)
  user = models.ForeignKey(User, unique=true)
  active = models.BooleanField(default=True)
๐Ÿ‘คArun Ghosh

Leave a comment