python中Flask数据库sqlalchemyORM层面外键和一对一关系实现插入数据时报错relationship ‘UserExtend.user’ will copy column user.id to column user_extend.uid, which conflicts with relationship(s): ‘User.extend’ (copies user.id to user_extend.uid). If this is not the intention, consider if these relationships should be linked with back_populates, or if viewonly=True should be applied to one or more if they are read-only. For the less common case that foreign key constraints are partially overlapping, the orm.foreign() annotation can be used to isolate the columns that should be written towards. The 'overlaps
ORM关系之一对一:
在sqlalchemy中,如果想要将两个模型映射成一对一的关系,那么应该在父模型中,指定引用的时候,要传递一个uselist=False
这个参数进去。就是告诉父模型,以后引用这个从模型的时候,不再是一个列表了,而是一个对象了
使用ORM一对一有好处,但今天说的不是好处,是在创建一对一关系表时出现的错误
小伙伴们实现ORM一对一插入数据时是不是出现这个错误
报错原因
这是其中一种ORM一对一创建的方式,为什么会报错?
原因是:两个或多个关系将在刷新时将数据写入同一列,但ORM在这两个关系之间没有任何类型的反向填充配置。解决方法通常是安装正确的 sqlalchemy.orm.back_populates配置。
上面的映射将生成警告:
SAWarning: relationship ‘Child.parent’ will copy column parent.id to column child.parent_id,
which conflicts with relationship(s): ‘Parent.children’ (copies parent.id to child.parent_id)
解决方案
Child.parent,Parent.children似乎是冲突的。解决方案是relationship.back_populates:
这里需要做指定主表,这样关系就不会冲突了。
第二种方式就不用指定: