Django Unique Together (with foreign keys)

后端 未结 6 825
独厮守ぢ
独厮守ぢ 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:16

    My 2 cents, complementing the accepted response from @Wolph

    You can add validation for it yourself though, simply overwrite the validate_unique method and add this validation to it.

    This is a working example code someone could find usefull.

    from django.core.exceptions import ValidationError
    
    
    class MyModel(models.Model):
    
        fk = models.ForeignKey(AnotherModel, on_delete=models.CASCADE)
    
        my_field = models.CharField(...)  # whatever
    
        def validate_unique(self, *args, **kwargs):
            super(MyModel, self).validate_unique(*args, **kwargs)
    
            if self.__class__.objects.\
                    filter(fk=self.fk, my_field=self.my_field).\
                    exists():
                raise ValidationError(
                    message='MyModel with this (fk, my_field) already exists.',
                    code='unique_together',
                )
    

提交回复
热议问题