3

I have the following model:

from django.db import models


class Artist(models.Model):

    TYPE_CHOICES = (
        ('Person', 'Person'),
        ('Group', 'Group'),
        ('Other', 'Other'),)

    name = models.CharField(max_length=100)
    type = models.CharField(max_length=20, choices=TYPE_CHOICES)

The problem is that if I create an object like this: Artist.objects.create(...) the type validation doesn't work. How can I activate the validation for this?

Nepo Znat
  • 3,000
  • 5
  • 28
  • 49

1 Answers1

2

You can make an (abstract) model that first performs validations before saving the object with:

class ValidatedModel(models.Model):

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        self.clean_fields()      # validate individual fields
        self.clean()             # validate constraints between fields
        self.validate_unique()   # validate uniqness of fields
        return super(ValidatedModel, self).save(*args, **kwargs)

and then for example use this in models like:

class Artist(ValidatedModel):

    TYPE_CHOICES = (
        ('Person', 'Person'),
        ('Group', 'Group'),
        ('Other', 'Other'),)

    name = models.CharField(max_length=100)
    type = models.CharField(max_length=20, choices=TYPE_CHOICES)

Note that the above will validate model object in case you call the .save() method (or some other function does that), but some methods circumvent calling the .save() method like Model.objects.bulk_create(..), etc.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555