Monday, March 24, 2014

Re: Model validation across relationships

Thanks for the reply. I had a (perhaps unreasonable) malaise that validation should be limited to the fields on a single model.

On Sunday, March 23, 2014 4:19:29 PM UTC-4, Simon Charette wrote:
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+unsubscribe@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/0b3f9b10-f20a-4684-81d7-f04a62bf3790%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment