简体   繁体   English

Django unique_together 日期验证约束

[英]Django unique_together constraint for date validation

I have following model:我有以下 model:

class Completion(models.Model):
    date_completed = models.DateTimeField(auto_now=False, auto_now_add=False)
    related_task = models.ForeignKey(Task, on_delete=models.CASCADE)

I need to check that each Completion have unique date (not datetime - only the date) for each Task (which is Completion 's related field).我需要检查每个Completion的每个 Task (这是Completion的相关字段)的唯一日期(不是 datetime - 只有日期)。 In other words, I need something like this:换句话说,我需要这样的东西:

class Meta:
    unique_together = [
        'date_completed__date',
        'related_task'
    ]

I know it does not work this way (and should not), so I would like to ask, how can I achieve the desired result (if it is possible altogether).我知道它不能以这种方式工作(也不应该),所以我想问一下,我怎样才能达到预期的结果(如果可能的话)。

One way would be to add a new attribute to hold just a DateField and use it for the constraint.一种方法是添加一个新属性以仅保存一个 DateField 并将其用于约束。 I recognize that doesn't do exactly what you ask, and would require allowing nulls first, converting current datetime values for the date only field but depending where you are with this process it may be feasible.我认识到这并不完全符合您的要求,并且需要首先允许空值,将当前日期时间值转换为仅日期字段,但取决于您在此过程中所处的位置,这可能是可行的。 As I understand, the uniqueness is enforced at the database level and a function to strip off the time probably isn't going to work.据我了解,唯一性是在数据库级别强制执行的,而去除时间的 function 可能不起作用。

In the unique_together sectionunique_together部分

the appropriate UNIQUE statements are included in the CREATE TABLE statement适当的 UNIQUE 语句包含在 CREATE TABLE 语句中

As a side note, the documentation suggests using UniqueConstraint as作为旁注,文档建议使用UniqueConstraint作为

Use UniqueConstraint with the constraints option instead.将 UniqueConstraint 与约束选项一起使用。

UniqueConstraint provides more functionality than unique_together. UniqueConstraint 提供了比 unique_together 更多的功能。 unique_together may be deprecated in the future. unique_together 将来可能会被弃用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM