django - Limit the number of records in a Model that can have a value per user -


i have model boolean field named is_active. want limit number of models user can have value of boolean field true 1.

class mymodel(models.model):     user = models.foreignkey(user)     is_active = models.booleanfield(default=false)     #...more fields ... 

initially going add unique_togeather = ("user", "is_active") entry meta -- of course limit number of false entries user can have -- need unlimited.

ideally, i'd solve @ database level prevent race conditions.

the models being created celery tasks importing data using mymodel.objects.get_or_create() -- possible race condition occur due level of concurrency celery workers.

you should create custom clean method on model.

from django.core.exceptions import validationerror django.db import models  class mymodel(models.model):     user = models.foreignkey(user)     is_active = models.booleanfield(default=false)     #...more fields ...      def clean(self):         if not self.pk , mymodel.objects.filter(user=self.user, is_active=true).exists():             raise validationerror('how no?') 

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -