C/C++教程

sqlalchemy中的back_populates和backref

本文主要是介绍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

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

这篇关于sqlalchemy中的back_populates和backref的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!