简体   繁体   中英

Error while inseting flask SQLAlchemy Inserting Data in a Many-to-Many Relationship with Association Table

I have such database with relationship many2many

association_table = db.Table('association',
                             db.Column('meal_id', db.Integer, db.ForeignKey('meals.id')),
                             db.Column('order_id', db.Integer, db.ForeignKey('orders.id'))
                             )

class Order(db.Model):
    __tablename__ = 'orders'
    id = db.Column(db.Integer, primary_key=True)
    data = db.Column(db.String)
    meals = db.relationship(
        "Meals", secondary=association_table, back_populates="orders"
    )
       
class Meals(db.Model):
    __tablename__ = 'meals'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String, unique=True)
    price = db.Column(db.Float)
    orders = db.relationship(
        "Order", secondary=association_table, back_populates="meals"
    )

I try to insert data to table Order

order_to_database = Order (data='05_03_2021',
                           meals = 1
                           )

db.session.add(order_to_database)
db.session.commit()

meals is id of meals. I go th error:

How should I solve this problem?

When using db.relationship ORM expects meals should be an Instance of Meals , not an integer.

breakfast_meal = Meal(id=1,title='Lunch',price=9)

order_to_database = Order(data='05_03_2021')
order_to_database.meals.append(breakfast_meal)

db.session.add(order_to_database)

db.session.commit()

If you are using already existing meal from database you can do:

   lunch_meal = Meal.query.filter(Meal.id==10).first()
   ....
   order_to_database.meals.append(lunch_meal)
   ....
   db.session.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM