0

该程序有一个表示两个用户之间关系的表:

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",
        on_delete=models.CASCADE,
        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")),
                name="%(app_label)s_%(class)s_unique_user_field",
            ),
        ]

第一个检查之间的唯一约束,第二个(user_from, user_to)检查user_fromisuser_to与正在创建。user_from=user1user_to=user2user_from=user2user_to=user1

是否存在某种形式来添加此约束?或者解决方案是仅在应用程序层创建约束?例如覆盖保存方法并检查此约束。

4

0 回答 0