2

我是 sqlAlchemy 的新手,我正在尝试在我的 Flask 应用程序中创建一个手动对象关系映射到一个已经存在的 postgresql 数据库。我正在使用本教程。但是它没有说明如何使用 backref 在模型之间创建关系。到目前为止,这是我的 models.py 类,唯一给我带来麻烦的是 backref。我正在尝试在用户和 F_League 之间创建一对多的关系(一个用户的许多幻想联盟)。当我运行我的文件 models.py 时,我收到以下错误:

<User u'ivan'>
<F_League  u'First Fantasy League'>
Traceback (most recent call last):
  File "app/models.py", line 86, in <module>
    print u1.leagues
  File "/home/ivan-manolov/Documents/fft/.env/local/lib/python2.7/site-packages/sqlalchemy/orm/properties.py", line 729, in __str__
    return str(self.parent.class_.__name__) + "." + self.key
AttributeError: 'RelationshipProperty' object has no attribute 'parent'

这是我的 models.py 文件:

from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref, mapper
from sqlalchemy import *
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine('postgresql://nfldb:nfldb@localhost/nfldb', convert_unicode=True, echo=False)
metadata=MetaData()
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))

def init_db():
    metadata.create_all(bind=engine)

class User(object):
        query=db_session.query_property()
        leagues=relationship("F_League",backref="fowner",lazy="dynamic") 
    def __init__(self, user_id=None, user_name=None, first_name=None, last_name=None, email=None, password=None, last_sign_out=None):
        self.user_id= user_id
        self.user_name=user_name
        self.first_name= first_name
        self.last_name= last_name
        self.email= email
        self.password=password
        self.last_sign_out= last_sign_out


    #def set_password(self, password):
         #   self.pwdhash = generate_password_hash(password)

        def check_password(self, password):
            return self.password==password

        def is_authenticated(self):
            return True

        def is_active(self):
            return True

        def is_anonymous(self):
            return False

        def get_id(self):
            return unicode(self.user_id)

    def __repr__(self):
            return '<User %r>' % (self.user_name)

users=Table('users',metadata,
    Column('user_id', Integer, primary_key=True),
    Column('user_name', String, unique=True, nullable=False),
    Column('last_name', String, nullable=False),
    Column('email', String,unique=True, nullable=False),
    Column('password', String),
    Column('last_sign_out', DateTime),

    )
mapper(User, users)

class F_League(object):
    query=db_session.query_property()  

    def __init__(self, league_id=None, user_id=None, league_name=None):
        self.league_id=league_id
        self.user_id=user_id
        self.league_name=league_name

    def __repr__(self):                                                    
        return '<F_League  %r>' % (self.league_name) 

fleagues=Table("f_league",metadata,
       Column( 'league_id', Integer, primary_key=True),
       Column('user_id', Integer, ForeignKey('users.user_id')),
       Column('league_name',String, unique=True)
       )
mapper(F_League, fleagues)



if __name__=="__main__":
    result=User.query.filter_by(user_name="ivan").first()
        print result
        league=db_session.query(F_League).join(User).filter_by(user_id=1).first()
        print league
        u1=User()
        f1= F_League()
        print u1.leagues

       # many1= db_session.query(User.leagues).join(User).filter_by(user_id=1).first()
        #print many1

提前谢谢你的帮助

4

1 回答 1

4

当您执行以下操作时,您错误地混合了声明性映射和经典映射的使用:

class User(object):
    query=db_session.query_property()

    # this is wrong
    leagues=relationship("F_League",backref="fowner",lazy="dynamic") 

    # ...

users=Table('users',metadata,
    # ...
)

mapper(User, users)

这是您的两个选择。

  1. 声明性:

    Base = declarative_base()
    
    class User(Base):
        __tablename__ = 'users'
    
        user_id = Column(Integer, priamry_key=True)
        user_name = Column(String)
    
        # ...
    
        leagues=relationship("F_League",backref="fowner",lazy="dynamic") 
    
  2. 古典:

    class User(object):
        query=db_session.query_property()
    
        # ...
    
    users=Table('users',metadata,
        # ...
    )
    
    mapper(User, users, properties={
        "leagues": relationship(F_League, backref="fowner", lazy="dynamic") 
    })
    
于 2013-11-02T22:02:36.383 回答