2012-04-21 66 views
0

我有一個模型User和一個模型Thing。 A User可以擁有零個或多個Thing s。 A Thing可能歸零或更多User s。通常我會在第三個表Thing_OwnershipUser s添加到Thing秒,但我想借的SQLAlchemy的backref功能的優勢,這樣,如果我有一個User實例george我可以打電話給george.inventory拿到屬於georgeThing的List 。沒有鏈接表/模型的多對多關係

什麼是最好的方式去做到這一點,或者我應該只是添加第三個模型,並實施User.inventory作爲搜索通過第三個Thing_Ownership模型的相關關係?

回答

3

查看關於Many to Many關係的SQLAlchemy文檔 - 它應該完全按照您要查找的內容進行操作。

所以,如果你有型號爲UserThing,你可以設置一個二級參數在你們的關係:

from sqlalchemy import Table, Integer, Column, ForeignKey 
from sqlalchemy.orm import relationship, backref 
from sqlalchemy.ext.declarative import declarative_base 

Base = declarative_base() 

association_table = Table('association', Base.metadata, 
    Column('user_id', Integer, ForeignKey('user.id')), 
    Column('thing_id', Integer, ForeignKey('thing.id')) 
) 

class User(Base): 
    __tablename__ = 'user' 
    # Whatever you need in this model 
    inventory = relationship('Thing', secondary = association_table, backref = 'users') 

class Thing(Base): 
    __tablename__ = 'thing' 
    # Whatever you need in this model 

然後,您可以通過調用訪問實例爲george的屬於UserThing個列表george.inventory

希望這會有所幫助。

編輯:重讀你的問題,看到你想用backref - 添加代碼來做到這一點。
編輯2:遺漏了一個非常重要的部分。