问题描述
class Contact(models.Model):
user_from = models.ForeignKey(
"User",on_delete=models.CASCADE,related_name="rel_to_from",help_text=_("Person who sent the contact request"),)
user_to = models.ForeignKey(
"User",related_name="rel_to_set",help_text=_("Person who receive the contact request"),)
....
问题出在约束上,我到目前为止定义的约束是:
....
class Meta:
constraints = [
models.UniqueConstraint(
fields=("user_from","user_to"),name="%(app_label)s_%(class)s_unique_user_field",),models.CheckConstraint(
check=~models.Q(user_from=models.F("user_to")),]
第一个检查 (user_from,user_to)
之间的唯一约束,第二个检查 user_from
与 user_to
不同,但两者都不会阻止使用角色互换,也就是说,如果在 user_from=user1
和 user_to=user2
处已经存在关系,则不会阻止创建 user_from=user2
和 user_to=user1
。
是否存在某种形式来添加此约束?或者解决方案是仅在应用层创建约束?,例如覆盖保存方法并检查此约束。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)