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
- Django and extending templates not working?
- Django update an instance using another instance
- REST Framework: how to serialize objects?
Source:stackexchange.com