2014-10-02 80 views
0

我正在構建配方數據庫。在這裏,有一些配料(如洋蔥,胡蘿蔔等)和改性劑(如切丁,去皮等),它們是改性成分的一部分,它是配方的一部分。我的models.py如下:創建行時映射器錯誤

from app import db 

modifiers = db.Table('modifiers', 
    db.Column('modified_ingredient', db.Integer, db.ForeignKey('modified_ingredient.id')), 
    db.Column('modifier', db.Integer, db.ForeignKey('modifier.id')) 
    ) 

modified_ingredients = db.Table('modified_ingredients', 
    db.Column('recipe', db.Integer, db.ForeignKey('recipe.id')), 
    db.Column('modified_ingredient', db.Integer, db.ForeignKey('modified_ingredient.id')) 
    ) 

class Recipe(db.Model): 
    __tablename__ = 'recipe' 

    id = db.Column(db.Integer, primary_key=True) 

    name = db.Column(db.String(256)) 
    description = db.Column(db.Text) 
    directions = db.Column(db.Text) 
    prep_time = db.Column(db.Integer) 
    cook_time = db.Column(db.Integer) 
    image = db.Column(db.LargeBinary()) 
    ingredients = db.relationship('modified_ingredient', secondary=modified_ingredients) 

class Ingredient(db.Model): 
    __tablename__ = 'ingredient' 

    id = db.Column(db.Integer, primary_key=True) 

    name = db.Column(db.String(30), index=True, unique=True) 

class Modifier(db.Model): 
    __tablename__ = 'modifier' 

    id = db.Column(db.Integer, primary_key=True) 

    name = db.Column(db.String(30), index=True, unique=True) 

class ModifiedIngredient(db.Model): 
    __tablename__ = 'modified_ingredient' 

    id = db.Column(db.Integer, primary_key=True) 

    amount = db.Column(db.Integer) 
    unit = db.Column(db.String(20)) 
    ingredients = db.relationship('ingredient', backref='ingredient', lazy='dynamic') 
    modifiers = db.relationship('Modifier', secondary=modifiers, 
     backref=db.backref('modifiers', lazy='dynamic'), lazy='dynamic') 
    recipe = db.Column(db.Integer, db.ForeignKey('recipe.id')) 

不過,如果我打開一個shell和類似輸入「onion = models.Ingredient(name='Onion')」我得到的錯誤:

sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Original exception was: relationship 'ingredients' expects a class or a mapper argument (received: <class 'sqlalchemy.sql.schema.Table'>) 

我不完全知道在哪裏我的設置出錯了。 謝謝。

回答

2

如果我讀的錯誤信息正確,則

ingredients = db.relationship('modified_ingredient', secondary=modified_ingredients) 

應該成爲錯誤消息

ingredients = db.relationship('ModifiedIngredient', secondary=modified_ingredients) 

注:

Original exception was: relationship 'ingredients' expects a class or a mapper argument (received: <class 'sqlalchemy.sql.schema.Table'>)

如果它需要一個類時,它是一個類:)