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?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/084d8f27-0014-47d0-83bd-29c11b50c645%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to