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?

Le vendredi 21 mars 2014 19:43:07 UTC-4, Joshua Pokotilow a écrit :
>
> 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/58d9ed08-c88d-4b0f-9e46-eb6a1e246650%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to