This is the schema of the database i am working with:
create table user(
id integer PRIMARY KEY,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL
);
create table photo (
id integer PRIMARY KEY,
path varchar(255) NOT NULL,
title varchar(255) NOT NULL,
userid integer NOT NULL,
FOREIGN KEY (userid) REFERENCES user(id)
);
This is the code i am trying to run:
from sqlalchemy import *
metadata = BoundMetaData("mysql://root@localhost/photo")
class User(object):
def __repr__(self):
return "user#%d: %s" % (self.id, self.email)
class Photo(object):
def __repr__(self):
return "photo#%d: %d" % (self.id, self.userid)
usertable = Table('user', metadata, autoload=True)
phototable = Table('photo', metadata, autoload=True)
usermapper.add_property('photos', relation(Photo))
u = User()
print u.photos
It fails with the following error:
Traceback (most recent call last):
File "photo1.py", line 22, in ?
u = User()
File "build/bdist.macosx-10.4-fat/egg/sqlalchemy/orm/mapper.py",
line 439, in init
File "build/bdist.macosx-10.4-fat/egg/sqlalchemy/orm/mapper.py",
line 166, in compile
File "build/bdist.macosx-10.4-fat/egg/sqlalchemy/orm/mapper.py",
line 184, in _compile_all
File "build/bdist.macosx-10.4-fat/egg/sqlalchemy/orm/mapper.py",
line 403, in _initialize_properties
File "build/bdist.macosx-10.4-fat/egg/sqlalchemy/orm/mapper.py",
line 1165, in init
File
"build/bdist.macosx-10.4-fat/egg/sqlalchemy/orm/properties.py", line
237, in do_init
sqlalchemy.exceptions.ArgumentError: Error determining primary
and/or secondary join for relationship 'photos' between mappers
'Mapper|User|user' and 'Mapper|Photo|photo'. You should specify the
'primaryjoin' (and 'secondaryjoin', if there is an association table
present) keyword arguments to the relation() function (or for backrefs,
by specifying the backref using the backref() function with keyword
arguments) to explicitly specify the join conditions. Nested error is
"Cant find any foreign key relationships between 'user' and 'photo'"
However, when i replaced the autoload with explicit Columns, it works
fine.
usertable = Table('user', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(255), nullable=False),
Column('email', String(255), nullable=False))
phototable = Table('photo', metadata,
Column('id', Integer, primary_key=True),
Column('userid', Integer, ForeignKey('user.id')),
Column('path', String(255), nullable=False),
Column('title', String(255), nullable=False))
Am i doing something wrong? Is autoload functionality not complete? or
is it a bug?
Please help!
anand