我想在ManyToManyField中使用Django排除约束。不幸的是,到目前为止,我的努力是徒劳的。这是我的约会模式:
从django.contrib.postgres.constraints导入ExclusionConstraint从django.contrib.postgres.fields导入DateTimeRangeField,RangeOperators
class Appointment:
patients = models.ManyToManyField(Patient, related_name='appointments' , blank=True )
datetimerange = DateTimeRangeField(null=False, blank = False )
doctor = models.ForeignKey(Doctor, related_name='doctor_appointments')
class Meta:
constraints = [
ExclusionConstraint(
name='unique_doctor',
expressions=[
('datetimerange', RangeOperators.OVERLAPS),
('doctor ', RangeOperators.EQUAL),
],
),
ExclusionConstraint(
name='unique_patients',
expressions=[
('datetimerange', RangeOperators.OVERLAPS),
('patients', RangeOperators.CONTAINED_BY)
],
condition= Q(is_archived=False) & Q(is_cancelled=False)
)
]不幸的是这不管用。引用博士的第一个约束非常有效,但第二个约束在迁移过程中给出了这个错误:
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedColumn: column "patient_id" named in key does not exist
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "patient_id" named in key does not exist这件事已经困扰我很长时间了。任何帮助都很感激。
发布于 2022-11-09 22:56:23
这里的问题是,约束必须在Appointment模型的表上进行,但是,由于patients是一个M2M字段,因此不存在错误消息所述的列。该关系基于持有外键的中间表。
的结果是,你不能完全做你想做的事情。
但是,您可以将此验证构建到模型的clean()方法中。
https://stackoverflow.com/questions/66700970
复制相似问题