我可以在Django模型中至少制作一个字段吗? [英] Can I make at least one field a requirement on a Django Model?
问题描述
class Person(models.Model):
name = models。 CharField(max_length = 50)
email = models.EmailField()
电话= models.CharField(max_length = 50)
对于每个人,我想确保有联系信息。我不需要电子邮件和电话(尽管两者都可以),但我需要确保提供至少一个。
我知道我可以检查这些东西在表单中,但是有没有办法我可以在模型/数据库级别来保存重复的自己?
撰写 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模型中至少制作一个字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!