Flask sqlAlchemy手册ORM:'RelationshipProperty'对象没有属性'parent'

时间:2013-10-28 18:03:15

标签: postgresql orm sqlalchemy flask flask-sqlalchemy

我是sqlAlchemy的新手,我正在尝试创建一个手动对象关系映射到我的Flask应用程序中已经存在的postgresql数据库。我正在使用this tutorial。但是,它没有说明如何使用backref在模型之间创建关系。到目前为止,这是我的models.py类,唯一给我带来麻烦的是backref。我正在尝试在User和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

提前感谢您的帮助

1 个答案:

答案 0 :(得分:4)

当您执行以下操作时,您错误地混合了declarativeclassical映射的使用:

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") 
    })