name the COUNTRY_ID column in lower case in your mapping, all UPPERCASE
means case sensitive and it will be quoted "COUNTRY_ID", and not match
the case-insensitive country_id name in your actual schema.
On 07/29/2016 03:29 PM, bsdz wrote:
> I did some further checking and realized deeper down the real issue lies
> column name case and with column_reflect where I map my column names to
> lower case. This seems to confuse the ForeignKey function.
>
> Here's a complete example with sqlite. Perhaps there's a simple workaround?
>
> |
> importsqlalchemy assa
> fromsqlalchemy.orm importsessionmaker,relationship
> fromsqlalchemy.ext.declarative importdeclarative_base,DeferredReflection
> fromsqlalchemy.eventimportlistens_for
>
> e =sa.create_engine("sqlite://",echo=True)
>
> e.execute("""
> create table country (
> COUNTRY_ID integer primary key
> )
> """)
>
> e.execute("""
> create table main.user (
> user_id integer primary key,
> COUNTRY_ID integer,
> foreign key (country_id) references country(country_id)
> )
> """)
>
> Base=declarative_base(cls=DeferredReflection)
>
> classCountry(Base):
> __tablename__ ='country'
>
> classUser(Base):
> __tablename__ ='user'
> __table_args__ ={'schema':'main'}
>
> country_id
> =sa.Column("COUNTRY_ID",sa.Integer,sa.ForeignKey('country.COUNTRY_ID'))
> country =relationship("Country",uselist=False)
>
> classMyModel(object):
> def__init__(self,env):
> self._engine =e
> Base.metadata.bind =self._engine
> Base.prepare(self._engine)
>
>
> defcreate_session_maker(self):
> returnsessionmaker(bind=self._engine)
>
> @listens_for(sa.Table,"column_reflect")
> defcolumn_reflect(inspector,table,column_info):
> """
> Map upper case column names to lower case.
> """
> column_info['key']=column_info['name'].lower()
>
> # This code is run in another module.
> mymodel =MyModel("DEV")
> Session=mymodel.create_session_maker()
> session =Session()
> l1 =session.query(User).all()
>
> print(User.country.property.primaryjoin)
> |
>
>
> The code above produces the following error:
>
> |
>
> NoReferencedColumnError:Couldnotinitialize target column
> forForeignKey'country.COUNTRY_ID'on table 'user':table 'country'has
> nocolumn named 'COUNTRY_ID'
>
>
> |
>
> Thanks again :)
>
>