Model validation across relationships

33 views
Skip to first unread message

Joshua Pokotilow

unread,
Mar 21, 2014, 7:43:07 PM3/21/14
to django...@googlegroups.com

Given these models, would UserProfile.clean() make sense as written?

class PhoneNumber(models.Model):
    user = models.ForeignKey(User, related_name='phone_numbers')
    phone_number = models.CharField(max_length=20)

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    sms_notifications_enabled = models.BooleanField(default=False)

    # Given these models / fields, does this implementation make sense?
    def clean(self):
        if self.sms_notifications_enabled:
            if not self.user.phone_numbers.exists():
                raise ValidationError("SMS notifications cannot be enabled because this user has no phone number")

I think it’s OK, but the documentation for Model.clean() seems somewhat vague about what sorts of checks one may implement. Specifically, it says, “This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field.”

Is the above code in line with best practices?

Simon Charette

unread,
Mar 23, 2014, 4:19:29 PM3/23/14
to django...@googlegroups.com
I'd say that's exactly what you should use `Model.clean()` for. In this case you're doing validation that requires access to more than a single field.

What sounds vague to you in the documentation?

Joshua Pokotilow

unread,
Mar 25, 2014, 12:28:12 AM3/25/14
to django...@googlegroups.com
Thanks for the reply. I had a (perhaps unreasonable) malaise that validation should be limited to the fields on a single model.
Reply all
Reply to author
Forward
0 new messages