sqlalchemy 一對多 關係

2021-07-24 17:46:24 字數 2486 閱讀 4872

import os

import sqlalchemy

from sqlalchemy import create_engine, column, integer, string, foreignkey, sequence

from sqlalchemy.ext.declarative  import declarative_base

from sqlalchemy.orm import sessionmaker, relationship

"""backref='addresses'  #直接使用表名

backref = backref('address')

backref = backref('address', order_by=id)

"""base_dir = os.path.abspath(os.path.dirname(__file__))

db_path = os.path.join(base_dir, 'data.one.many.sqlite')

engine = create_engine('sqlite:///' + db_path, echo=true)

base = declarative_base()

session = sessionmaker(bind=engine)

session = session()

class user(base):

__tablename__ = 'users'     # user類對映到users表

id = column(integer, sequence("user_id_seq"), primary_key=true) # sequence表示id自增長, 主鍵       name = column(string)

fullname = column(string)

password = column(string) 

def __init__(self, name, fullname, password):

self.name = name

self.fullname = fullname

self.password = password     

def __repr__(self):

return "< user (name = '%s', fullname='%s', password='%s')>" %( self.name, self.fullname, self.password  )

class address(base):

__tablename__ = 'addresses'      # address類對映到addresses表

#id = column(integer, primary_key=true)    

id = column(integer, sequence("user_id_seq"), primary_key=true) # sequence表示id自增長, 主鍵    

email_address = column(string, nullable=false)

user_id = column(integer, foreignkey('users.id'))   # 多對一。此表的外來鍵就是 users表中的主鍵,id.多個address屬於乙個user

user_view = relationship("user", back_populates='addresses')    # 使用者和位址關係表,沒有實際資料庫表,只是乙個關係對照表

def __init__(self,email_address):

self.email_address = email_address        

def __repr__(self):

return ""  % self.email_address

user.addresses = relationship("address", order_by=address.id, back_populates="user_view") # 在user類中增加乙個位址屬性,指向位址的對照表

base. metadata.create_all(engine)

#使用zhangsan = user('zs','zhangsan', 'abc222')   # 設定使用者名稱

lisi = user('ls','lisi', '123456') 

# 使用者郵址

zhangsan.addresses = [

address(email_address="[email protected]"),

address(email_address="[email protected]"),

]lisi.addresses = [

address(email_address="[email protected]"),

address(email_address="[email protected]"),

]session.add_all([zhangsan, lisi])

session.commit()

Mvc Entityfraome一對多關係對映

第一資料庫建立 第二建立mvc ef專案 注意要點 如下資料庫表 t classes,t students 建立兩個類與資料庫表相對應 public class class public string name public virtual icollectionstudent new list p...

hibernate 一對多關係

1.首先在實體類描述資料庫主外來鍵關係,比如 我有多個訂單項 private setoritems new hashset 在order item定義order 屬性 2.需要在對映的實體類描述關係,我這裡是乙個訂單有多個訂單項 order.hbm.xml order item.hbm.xml 關於...

Entity Framework 一對多關係對映

ef中關係對映也是乙個很關鍵的內容,關係對映和屬性對映一樣,也是在onmodelcreating中配置對映。ef中的關係對映有如下三種 one to many relationship 一對多 many to many relationship 多對多 one to one relationship...