A unique combination of constraints, including a specific field value

For one of my models, I need to provide unicity for some lines, but only in a specific case. Only "verified" lines should follow this restriction.

Basically, I look forward to something like

class MyModel(models.Model):
    field_a = models.CharField()
    field_b = models.CharField()
    validated = models.BooleanField(default=False)

    class Meta:
        unique_together = (('field_a', 'field_b', 'validated=True'),)
+4
source share
2 answers

You cannot do this using unique_togetherDjango, presumably because not all the databases supporting it will support it.

You can do this at the application level by checking the model:
https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects

eg,

class MyModel(models.Model):
    field_a = models.CharField()
    field_b = models.CharField()
    validated = models.BooleanField(default=False)

    def clean(self):
        if not self.validated:
            return
        existing = self.__class__.objects.filter(field_a=self.field_a,
                                                 field_b=self.field_b).count()
        if existing > 0:
            raise ValidationError(
                "field_a and field_b must be unique if validated=True"
            )

, , , , ..

instance.clean()
instance.save()

. , ModelForm, ..

if form.is_valid():
    instance = form.save()
+7

. :

def save(self, **kwargs):
    try:
        self.objects.get(field_a=self.field_a, field_b=self.field_b, validated=True)

        # this wont run if the previous line throw an exception
        raise ValidationError(
            "field_a and field_b must be unique if validated=True"
        ) 

    except self.__class__.DoesNotExist:  # does not catch the ValidationError 
        super(MyModel, self).save(**kwargs)  # everything cool

clean().

+1

Source: https://habr.com/ru/post/1528146/


All Articles