2017-12-10 15 views
0

documentation을 가지고 다음 표를 정의하고 채웠지 만 관계는 아직 정의되지 않았습니다.Reflection 후 SQLAlchemy에서 many to many 관계 추가하기

class CountryAssociation(Base): 
    __tablename__ = 'Country_Region_Mapping' 
    country_id = Column(Integer, ForeignKey('countries.uid'), primary_key=True) 
    region_id = Column(Integer, ForeignKey('regions.uid'), primary_key=True) 
    region = relationship('Region', back_populates='country') 
    country = relationship('Countries', back_populates='region') 
    extra_data = Column(String(50)) 

class Countries(Base): 
    __tablename__ = 'countries' 
    uid = Column(Integer, primary_key=True) 
    countryname = Column('English_short_name', 
      String(255), unique=True, nullable=False) 
    region = relationship('CountryAssociation', 
      back_populates='country') 

class Region(Base): 
    __tablename__ = 'regions' 
    uid = Column(Integer, primary_key=True) 
    region = Column(String(255), unique=True, nullable=False) 
    country = relationship('CountryAssociation', 
     back_populates='region') 

이제 테이블간에 많은 관계를 만들고 싶습니다. docs

Base = automap_base() #reflecting the orm way 
engine = create_engine('sqlite:///mydatabse.db') 

Base.prepare(engine, reflect=True) 

Session = sessionmaker(bind=engine) 
session = Session() 

table_countries = Base.classes.countries 
table_regions = Base.classes.regions 

r = session.query(table_regions).filter(table_regions.region == "Western Europe").first() 
c = session.query(table_countries).filter(table_countries.English_short_name == "Germany").first() 

c.region.append(r) # this fails with 

AttributeError은 '국가의 목적은 어떤 속성'지역 '이 그러나 작동

이 없습니다 : 내가 잘못 여기에 (초급) 뭐하는 거지 얻을 해달라고

c.countryname # Germany 

을 ...

+0

가 반사 ([협회 개체]와 http://docs.sqlalchemy.org/en/을 작동하지 않습니다 그것을 가능 rel_1_1/orm/basic_relationships.html # association-object)? – Bjoern

+0

http://docs.sqlalchemy.org/ko/latest/orm/extensions/associationproxy.html#simplifying-association-objects를 보셨습니까? – plumSemPy

+0

'c.countryname' 작업은 매우 이상하게 보입니다. 원래 클래스 정의를 만들 때'Base = automap_base()'를 사용했음을 알릴 수도 있습니다. –

답변

0

association object patternextra_data으로 사용 했으므로 automap relationship detection은 (는)을 인식하지 못합니다.secondary table of a many to many A와 :

  1. If the table contains two and exactly two ForeignKeyConstraint objects, and all columns within this table are members of these two ForeignKeyConstraint objects, the table is assumed to be a “secondary” table, and will not be mapped directly.

다른 방법을 넣어 : 테이블 하지 보조 그래서하지 Country_Region_Mapping 내의 모든 열이 외부 키 제약의 구성원이 만든 많은 관계로 그래서 많은 사람들이, 없다.

간과 한 또 다른 사항은 naming scheme입니다. 작동중인 보조 테이블이있는 경우 작성된 ​​관계는 복수 테이블 이름 때문에 named regions_collection by default이됩니다.

무엇이 일어나는가하면 많은 하나에/한 regionsCountry_Region_MappingcountriesCountry_Region_Mapping 사이의 많은 관계가 생성된다는 것입니다 : 인해 복수의 테이블에 Country_Region_Mapping에 스칼라 관계를 속성 이름을 지정하는 것이

In [22]: table_countries.country_region_mapping_collection 
Out[22]: <sqlalchemy.orm.attributes.InstrumentedAttribute at 0x7f2d600fb258> 

In [23]: table_regions.country_region_mapping_collection 
Out[23]: <sqlalchemy.orm.attributes.InstrumentedAttribute at 0x7f2d600fbaf0> 

In [28]: table_country_region_mapping.countries 
Out[28]: <sqlalchemy.orm.attributes.InstrumentedAttribute at 0x7f2d535a2990> 

In [29]: table_country_region_mapping.regions 
Out[29]: <sqlalchemy.orm.attributes.InstrumentedAttribute at 0x7f2d535a2938> 

주 또한 복수 명명이 가능합니다. 마음이와

당신과 같이 새로운 연결을 추가 할 것 :

In [36]: c.country_region_mapping_collection.append(
    ...:  Base.classes.Country_Region_Mapping(countries=c, regions=r))