双向外键:无ORM声明式实现数据库级图关联
突破外键单向约束,通过PostgreSQL Exclusion Constraint与触发器实现双向关联,允许外键互相指向并自动维护对称性。 · 难度:入门 · +10XP
双向外键:无ORM声明式实现数据库级图关联
例如Twitter的互关关系:如果A关注B,则B关注A。传统做法是存储两条记录。本教程演示如何通过一个中间表+Exclusion Constraint确保双向引用的唯一性,并利用PostgreSQL的触发器在插入一条记录时自动生成反向记录。Django层面则用多对多through模型+自定义管理器透明地处理。
from django.db import models
class BidirectionalFollow(models.Model):
from_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follows')
to_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followed_by')
class Meta:
constraints = [
models.UniqueConstraint(fields=['from_user', 'to_user'], name='unique_follow'),
# 通过数据库触发器保证对称性
]