sqlalchemy一對多的關係

#encoding: utf-8

from sqlalchemy import create_engine,Column,Integer,String,Float,func,and_,or_,Text,\ ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker,relationship from random import randint HOSTNAME = '127.0.0.1' PORT = 3306 DATABASE = 'first_sqlalchemy' USERNAME = 'root' PASSWORD = '123456'

#dialect+driver://username:password@host:port/database
DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/" \ "{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE) engine = create_engine(DB_URI) Base = declarative_base(engine) # Session = sessionmaker(engine) # session = Session()
 session = sessionmaker(engine)() #Session(**local_kw)

#父表/從表 #user/article


class User(Base): __tablename__ = 'user' id = Column(Integer,primary_key=True,autoincrement=True) username = Column(String(32),nullable=False) # articles = relationship("Article") #獲取用戶發佈全部文章


class Article(Base): __tablename__ = 'article' id = Column(Integer,primary_key=True,autoincrement=True) title = Column(String(50),nullable=False) content = Column(Text,nullable=False) uid = Column(Integer,ForeignKey('user.id',ondelete='RESTRICT')) author = relationship('User',backref='articles') #sqlalchemy orm提供的

# Base.metadata.drop_all() # # Base.metadata.create_all() # # # #添加數據 # user = User(username = 'xiaowu') # session.add(user) # session.commit() # # article = Article(title = '聖墟',content = '吹牛逼死坑的小說,每天吹水逼',uid = 1) # session.add(article) # session.commit()

#如今有個需求,我要查詢article表中關聯user表的數據,同過uid查詢
''' article = session.query(Article).first() uid = article.uid user = session.query(User).get(uid) #get根據主鍵會對一個對象或None print(user) '''
#上面寫法也行,可是有沒有更簡便的呢? # from sqlalchemy.orm import relationship #sqlalchemy爲咱們提供了 relationship
 article = session.query(Article).first() #獲取user對象
user = article.author print(user) #經過author這個字段就能直接查詢出User全部關聯的內容
author_name = user.username print(author_name) #我如今又另外一個需求,獲取用戶發佈的文章,該怎麼作, #首先咱們要明白用戶跟文章的關係,是 一對 多關係
 user = session.query(User).first() article= user.articles print(article)#獲取文章對象 ,[<__main__.Article object at 0x0000021D7BA2FC18>]是列表

#獲取用戶發佈的文件title
 article_title = article[0].title print(article_title) #這時候就有疑問呢,一樣是用relationship,爲何獲取對象的類型卻不同,
''' User (主表)對 Aritcle(子表) relationship 獲取 aritcle的對象是列表包裹着的 而 Aritcle(子表) 對 User(主表)relationship 獲取 user 的對象 就是 內存對象 要理解這種作法,就要理解一對多關係,user(用戶)能夠發表多篇文章,而 article(文章) 只能有一個用戶發佈,因此獲取article的對象是列表包裹着的 '''

#如今有一個需求 能不能 簡化 relationship ,在子表顯示 #author = relationship('User',backref='articles')
''' backref 就是反關聯的意思,反向引用, article 經過 author 這個關鍵字 正向引用 user表中的字段 user 經過 articles 反向引用 article表中的字段 '''
相關文章
相關標籤/搜索