对于每个人,我想确保有联系信息。我不需要电子邮件和电话(尽管两者都可以),但我需要确保提供至少一个。
我知道我可以检查这些东西在表单中,但是有没有办法我可以在模型/数据库级别来保存重复的自己?
解决方案撰写 clean 方法。
from django.core.exceptions import ValidationError class Person(models.Model): name = models.CharField(max_length = 50) email = models.EmailField() phone = models.CharField(max_length = 50) def clean(self):如果没有(self.email或self.telephone): raise ValidationError(你必须指定电子邮件或电话)如果您使用模型表单(例如,在Django管理员中) Django会为您调用 clean 方法。换句话说,如果直接使用ORM,可以调用 full_clean() 方法手动实例。
Say I have a Person model:
class Person(models.Model): name = models.CharField(max_length=50) email = models.EmailField() telephone = models.CharField(max_length=50)For every Person I want to ensure that there is contact information. I don't need both email and telephone (though both is okay) but I need to ensure that at least one is provided.
I know I can check this stuff in forms, but is there a way I can do this at Model/database level to save repeating myself?
解决方案Write a clean method for your 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 you use a model form (e.g. in the Django admin), Django will call the clean method for you. Alteratively, if you are using the ORM directly, you can call the full_clean() method on the instance manually.
更多推荐
我可以在Django模型中至少制作一个字段吗?
发布评论