Can I make at least one field a requirement on a Django Model? -


say have person model:

class person(models.model):     name = models.charfield(max_length=50)      email = models.emailfield()     telephone = models.charfield(max_length=50) 

for every person want ensure there contact information. don't need both email , telephone (though both okay) need ensure at least one provided.

i know can check stuff in forms, there way can @ model/database level save repeating myself?

write clean method model.

from django.core.exceptions import validationerror   class person(models.model):     name = models.charfield(max_length=50)     email = models.emailfield()     telephone = models.charfield(max_length=50)      def clean(self):         if not (self.email or self.telephone):             raise validationerror("you must specify either email or telephone") 

if use model form (e.g. in django admin), django call clean method you. alteratively, if using orm directly, can call full_clean() method on instance manually.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -