Tinker
Tinker

Reputation: 4535

How do you check if first and last name are unique only on creation?

I have the following model:

class Person(models.Model):
    short_name = models.CharField(max_length=64)
    long_name = models.CharField(max_length=64)

and I have the following form:

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ['short_name', 'long_name']

Right now I am using this form for both update and create.

I would like this form to raise ValidationError if someone is trying to create a Person with the same short_name and long_name.

However, I do not want to raise an exception if a user is modifying an existing user's data.

I have thought about writing a clean method to check if Person.objects.filter(long_name=X, short_name=Y).count() returns anything but this condition incorrectly fails when I am modifying an existing instance.

How would you change this?

Upvotes: 0

Views: 143

Answers (2)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48952

An existing instance is one that has a value for pk. So just check for that in your clean() method:

class Person(models.Model):
    short_name = models.CharField(max_length=64)
    long_name = models.CharField(max_length=64)

    def clean(self):
        if self.pk is None and Person.objects.filter(long_name=self.long_name,
                                                     short_name=self.short_name).exists():
            raise ValidationError("Someone already has those names!")

Upvotes: 1

robotHamster
robotHamster

Reputation: 649

You can do this by using unique_together as illustrated here in the django documentation at the model level

Upvotes: 1

Related Questions