如何正确使用association_proxy和ordering_list与SQLAlchemy

时间:2014-01-22 19:58:57

标签: python sqlalchemy flask

基于SQLAlchemy Google Group上的一些帖子:

https://groups.google.com/forum/#!topic/sqlalchemy/S4_8PeRBNJw https://groups.google.com/forum/#!topic/sqlalchemy/YRyI7ic1QkY

我假设我可以成功使用assocation_proxyordering_list扩展来在两个模型之间创建有序的,多对多的关系,例如下面的Flask / SQLAlchemy代码:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.orderinglist import ordering_list

app = Flask(__name__)
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
db = SQLAlchemy(app)


class Image(db.Model):
    __tablename__ = 'images'

    id = db.Column(db.Integer, primary_key=True)
    filename = db.Column(db.String(255))


class UserImage(db.Model):
    __tablename__ = 'user_images'

    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True)
    image_id = db.Column(db.Integer, db.ForeignKey('images.id'), primary_key=True)
    image = db.relationship('Image')
    position = db.Column(db.Integer)


class User(db.Model):
    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))

    _images = db.relationship('UserImage',
        order_by='UserImage.position',
        collection_class=ordering_list('position'))
    images = association_proxy('_images', 'image')


with app.app_context():
    db.create_all()
    user = User(name='Matt')
    user.images.append(Image(filename='avatar.png'))
    db.session.add(user)
    db.session.commit()

if __name__ == '__main__':
    app.run()

但我最终得到了以下追溯:

$ python app.py
Traceback (most recent call last):
  File "app.py", line 44, in <module>
    user.images.append(Image(filename='avatar.png'))
  File "/Users/matt/.virtualenvs/sqlalchemy-temp/lib/python2.7/site-packages/sqlalchemy/ext/associationproxy.py", line 595, in append
    item = self._create(value)
  File "/Users/matt/.virtualenvs/sqlalchemy-temp/lib/python2.7/site-packages/sqlalchemy/ext/associationproxy.py", line 522, in _create
    return self.creator(value)
TypeError: __init__() takes exactly 1 argument (2 given)

这是不可能还是我做了一些公然错误的事?

1 个答案:

答案 0 :(得分:22)

sooo close; - )

请阅读association_proxy分机的Creation of New Values部分 为了使您的代码有效,您可以

选项-1 :将以下构造函数添加到UserImage类:

def __init__(self, image):
    self.image = image

选项-2 :使用您的函数覆盖默认creator

images = association_proxy('_images', 'image',
    creator=lambda _i: UserImage(image=_i),
    )

我个人赞成后者。