Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango custom unique together constraint
    text
    copied!<p>I have a users share model something like below:</p> <pre><code>class Share( models.Model ): sharer = models.ForeignKey(User, verbose_name=_("Sharer"), related_name='sharer') receiver = models.ForeignKey(User, verbose_name=_("Receiver"), related_name='receiver') class Meta: unique_together = ( ("sharer", "receiver"), ("receiver", "sharer") ) </code></pre> <p>I want to save a single object for sharer(S) and receiver(R) (order doesn't matters R-S or S-R). but above unique_together will not fulfil this; Suppose R-S is in database and then if I save S-R I will not get validation for this. For this I have written custom unique validation for Share model.</p> <pre><code> def validate_unique( self, *args, **kwargs): super(Share, self).validate_unique(*args, **kwargs) if self.__class__.objects.filter( Q(sharer=self.receiver, receiver=self.sharer) ).exists(): raise ValidationError( { NON_FIELD_ERRORS: ('Share with same sharer and receiver already exists.',) } ) def save(self, *args, **kwargs): # custom unique validate self.validate_unique() super(Share, self).save(*args, **kwargs) </code></pre> <p>This method works fine in normal use.</p> <p><strong>Problem:</strong> I have an matching algorithm which gets a share's and a receiver's requests and saves Share object(either S-R or R-S) then send them response(share object) <strong><em>at almost same time</em></strong>. As I am checking duplication with query(no database level) it takes time, so at the end I have 2 Objects S-R and R-S.</p> <p>I want some solution for this that for a sharer S and a receiver R I can only save single share object, either S-R or R-S else get some validation error(like IntegrityError of databse).</p> <p>Django=1.4, Database=Postgresql</p>
 

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