我如何在 django 中比较两个模型字段?
我的 Models.py 文件中有这个模型。我想比较“start_date”和“end_date”,以便 start_date 值永远不会大于 end_date,反之亦然。我如何进行此验证?
class Completion(models.Model):
start_date = models.DateField()
end_date = models.DateField()
batch = models.ForeignKey(Batch)
topic = models.ForeignKey(Topic)
I have this Model in my Models.py file.I want to to compare "start_date" and "end_date" so that start_date value would never be greater then end_date or vice-versa.How do i do this validation?
class Completion(models.Model):
start_date = models.DateField()
end_date = models.DateField()
batch = models.ForeignKey(Batch)
topic = models.ForeignKey(Topic)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将开始让您了解模型验证框架。
http:https://docs .djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model.clean
它由 ModelForms 使用,并且开始很有意义使用它。
基本上,您可以在模型中定义一个
clean()
方法,放入验证逻辑,并在失败时引发ValidationError
。这里的好处是任何
ModelForm
(这意味着管理站点也会调用full_clean()
,这反过来会调用您的模型clean()
无需任何额外工作。无需覆盖
save_model
,您将在管理表单顶部看到常见的验证错误。最后,它非常方便。您可以在任何地方使用它。
I'd start getting your head into the Model Validation framework.
http:https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model.clean
It's used by
ModelForms
and just makes a whole lot of sense to start using it.Basically, you'd define a
clean()
method in your model, put in your validation logic, and raiseValidationError
if it fails.The benefit here is that any
ModelForm
(which means the admin site too will callfull_clean()
, which in turn calls your modelclean()
without any extra work.No need to override
save_model
, you'll get the usual validation errors at the top of the admin form.Finally, it's super convenient. You can use it anywhere.