Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there any more elegant way to add a value sensitive unique together constraint in Django Model?
    primarykey
    data
    text
    <p>Here is the problem:</p> <p>I have a model like this:</p> <pre><code>class UserBook(models.Model): user = models.ForeignKey(User) book = models.ForeignKey(Book) is_active = models.BooleanField(default=False) class Meta: unique_together = ("user", "book") </code></pre> <p>Obviously, this model already has a unique together constraint for field <strong>user</strong> and <strong>book</strong>. And probably there will be some entries like this in the database:</p> <pre><code> ------------------------------ |user_id book_id is_active | | 1 1 0 | | 1 2 0 | | 1 3 1 | ------------------------------ </code></pre> <p>And I have one more constraint to add, which is each user can have at most one entry that the value of <strong>is_active</strong> field is 1(True).</p> <p>Currently I solve this problem by changing the model into this:</p> <pre><code>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) </code></pre> <p>Add a field <strong>key</strong>, and customize the <strong>save</strong> method of this model.</p> <p>But the <strong>max_length</strong> cannot be greater than 255 in this approach(which is no need to worry in my case, but sometimes the <strong>key</strong> field may be very long).</p> <p>So, I would like to know if there is any more elegant approach to solve this kind of problem.</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload