sqlalchemy中的back_populates和backref

# 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

这两种方法,都可以随着另一个字段的更新而更新。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在FastAPI,使用SQLAlchemy进行数据库操作时,可以使用relationship来定义表之间的关系,以便在查询一个模型时可以轻松地访问另一个模型。如果定义了一个relationship,并且使用了back_populates参数,则可以在两个模型之间建立双向关系。 例如,假设我们有一个User模型和一个Item模型,我们希望在查询Item模型时可以轻松地访问其所有者,同时在查询User模型时可以轻松地访问其所有项目,我们可以在定义关系时使用back_populates参数: ```python from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.orm import relationship class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) email = Column(String(50), unique=True, nullable=False) password_hash = Column(String(128), nullable=False) is_active = Column(Boolean(), default=True, nullable=False) items = relationship("Item", back_populates="owner") class Item(Base): __tablename__ = "items" id = Column(Integer, primary_key=True, index=True) title = Column(String(50), nullable=False) description = Column(String(100)) owner_id = Column(Integer, ForeignKey("users.id")) owner = relationship("User", back_populates="items") ``` 在上面的代码,我们在User模型和Item模型之间定义了一个关系,使用back_populates参数建立了双向关系。具体来说,我们在User模型定义了一个名为items的属性,并在Item模型定义了一个名为owner的属性,这两个属性都与对方的模型相关联。 在使用back_populates参数时,需要注意以下几点: 1. back_populates参数必须在两个模型的关系属性都使用,并且值必须相同。 2. 如果您使用了backref参数来定义关系,那么可以使用backref替换back_populates。 3. 如果您的模型之间有多个关系,那么需要使用不同的back_populates值来区分它们。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值