我可以在Django模型中至少制作一个字段吗?

编程入门 行业动态 更新时间:2024-10-23 17:31:43
本文介绍了我可以在Django模型中至少制作一个字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 说我有一个人模型:

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模型中至少制作一个字段吗?

本文发布于:2023-10-23 02:10:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519432.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   模型   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!