# coding:utf-8 from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:root001@127.0.0.1:3306/test", max_overflow=5) Base = declarative_base() class Identification(Base): __tablename__ = 'idents' id = Column(Integer, primary_key=True) address = Column(String(64), unique=True) users = relationship('User', back_populates='idents', uselist=False) def __repr__(self): return '<Identification %s>' % self.id class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(64), unique=True) sex = Column(String(64), unique=True) ident_id = Column(Integer, ForeignKey('idents.id')) idents = relationship('Identification',back_populates='users') def __repr__(self): return '<User %s>' % self.name i = Identification(id=123,address='hebei') u1 = User(name='yuner',sex='female') i.users=u1 print(u1.idents) print(i.users) u1.idents = i # 为123id指定了固定的用户, print(u1.idents) print(i.users) # 输出结果 <Identification 123> <User yuner> <Identification 123> <User yuner>
简而言之,back_populates的使用必须要两个表都要使用,当id指定了相应的用户,他们就相当于两个电脑通信了,可以共享对方的相应的属性。
# coding:utf-8 from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:root001@127.0.0.1:3306/test", max_overflow=5) Base = declarative_base() class Identification(Base): __tablename__ = 'idents' id = Column(Integer, primary_key=True) address = Column(String(64), unique=True) user = relationship('User', backref='ident', uselist=False) def __repr__(self): return '<Identification %s>' % self.id class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(64), unique=True) sex = Column(String(64), unique=True) ident_id = Column(Integer, ForeignKey('idents.id')) def __repr__(self): return '<User %s>' % self.name i = Identification(id=123,address='hebei') u1 = User(name='yuner',sex='female') u1.idents = i # 为123id指定了固定的用户, print(u1.ident) print(i.user) i.user=u1 print(u1.ident) print(i.user) # 输出结果 None None <Identification 123> <User yuner>
简而言之,backref使用的时候,只有一方来规定就可以,另一方不用做处理。而且页只能一方引用对方的属性,不能相互,从u1.indets就可以看出区别。
relationship的backref和backref()函数可以用来代替relationship.back_populates的方法,但是要在backref上指定userlist
这两种方法,都可以随着另一个字段的更新而更新。