python - Is there any more elegant way to add a value sensitive unique together constraint in Django Model? -


here problem:

i have model this:

class userbook(models.model):     user = models.foreignkey(user)     book = models.foreignkey(book)     is_active = models.booleanfield(default=false)      class meta:         unique_together = ("user", "book") 

obviously, model has unique constraint field user , book. , there entries in database:

    ------------------------------     |user_id  book_id  is_active |     |      1        1          0 |     |      1        2          0 |     |      1        3          1 |     ------------------------------ 

and have 1 more constraint add, each user can have @ 1 entry value of is_active field 1(true).

currently solve problem changing model this:

class userbook(models.model):     user = models.foreignkey(user)     book = models.foreignkey(book)     is_active = models.booleanfield(default=false)     key = models.charfeild(max_length=255, unique=true)      class meta:         unique_together = ("user", "book")      def save(self, *args, **kwargs):         if self.is_active:             self.key = "%s_%s" %(self.user_id, self.is_active)         else:             self.key = "%s_%s_%s" %(self.user_id, self.is_active, self.book_id) 

add field key, , customize save method of model.

but max_length cannot greater 255 in approach(which no need worry in case, key field may long).

so, know if there more elegant approach solve kind of problem.

thanks!

redefine is_active follows:

# equals user id if active; otherwise null. is_active = models.integerfield(null = true, unique = true) 

the user ids unique in column (satisfying desired constraint) , many null values in column won't violate constraint, discussed here.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -