Django Unique Together (with foreign keys)

后端 未结 6 839
独厮守ぢ
独厮守ぢ 2020-11-28 11:35

I have a situation where I want to use the Meta options of unique_together to enforce a certain rule, here\'s the intermediary model:



        
6条回答
  •  日久生厌
    2020-11-28 12:01

    from django.core.exceptions import ValidationError
    
    .....
    
    class UserProfileExtension(models.Model):
        extension = models.ForeignKey(Extension, unique=False)
        userprofile = models.ForeignKey(UserProfile, unique=False)
        user = models.ForeignKey(User, unique=False)  
    
        def validate_unique(self, *args, **kwargs):
            super(UserProfileExtension, self).validate_unique(*args, **kwargs)
            query = UserProfileExtension.objects.filter(extension=self.extension)
            if query.filter(userprofile__client=self.userprofile.client).exists():
                raise ValidationError({'extension':['Extension already exits for userprofile__client',]})
    

    The first query is to filter all records in UserProfileExtension model which has the same extension we are putting in the current record.

    Then we filter the query returned to find if it already contains userprofile__client which we are passing in the current record.

提交回复
热议问题