python - 多对多关系中的唯一约束
问题描述
我正在做一个 python 项目。在这个项目中,我使用的是 sqlalchemy。有两个表:notes 和 tags 以及创建多对多关系的第三个表 notes_tags。第三个表是这样定义的:
class NotesTags(Base):
__tablename__ = 'notes_tags'
id = Column(Integer, primary_key=True)
note_id = Column('note_id', Integer, ForeignKey('notes.id'))
note = relationship(Notes)
tag_id = Column('tag_id', Integer, ForeignKey('tags.id'))
tag = relationship(Tags)
当我将记录保存到此表时,我这样做:
notesTags.tag = newtag
notesTags.note = givenNote
session.add(notesTags)
在我的数据库中,我得到如下信息:
+----+---------+--------+
| id | note_id | tag_id |
+----+---------+--------+
| 1 | 83 | 1 |
| 2 | 108 | 1 |
| 3 | 114 | 1 |
| 4 | 119 | 1 |
| 5 | 124 | 1 |
+----+---------+--------+
5 rows in set (0.000 sec)
但是,如果我再次运行该过程,记录会重复,这意味着我会得到这样的东西:
+----+---------+--------+
| id | note_id | tag_id |
+----+---------+--------+
| 1 | 83 | 1 |
| 2 | 108 | 1 |
| 3 | 114 | 1 |
| 4 | 119 | 1 |
| 5 | 124 | 1 |
| 6 | 83 | 1 |
| 7 | 108 | 1 |
| 8 | 114 | 1 |
| 9 | 119 | 1 |
| 10 | 124 | 1 |
+----+---------+--------+
10 rows in set (0.000 sec)
这不是预期的结果。如何确保记录不重复?我想到了以下几点:a)在我保存记录之前检查是否已经存在具有给定 note_id - tag_id 的记录。b) 为使用 note_id 和 tag_id 的表创建复合 id
我不确定如何创建第二个以及什么是实现的最佳选择,或者我还能如何实现这一点。
如果这有什么不同,我将连接到 mysql 数据库。
任何帮助,将不胜感激。
解决方案
推荐阅读
- xml - 错误:文档中没有引用语法约束(DTD 或 XML 模式)
- pytorch - 将整数转换为二进制位的 pytorch 张量
- angular - Chrome 子链接中的 Angular
- google-cast - 无法暂停、恢复、更改在 chromecast 上播放的 VMAP 广告的音量
- python - 如何在 seaborn 联合网格/联合图中注释边缘图/分布图
- javascript - 如何显示下个月的 Laravel FullCalendar
- html - 如何在 agora 订阅直播视频?
- matlab - 如何从 Matlab 中的矩阵中随机选择 x 个索引
- c++ - 如何在 Visual Studio 中查看 std::mutex 的锁定线程?
- mysql - 如何编写查询以从数据库表中获取最近的记录