SQLAlchemy sessions error

前端 未结 3 927
无人共我
无人共我 2020-12-19 07:47

Background: Flask / Flask-SQLAlchemy / Flask-WTF, using declarative and scoped session

Simple POST operation:

@tas.route(\'/order_add\         


        
3条回答
  •  轮回少年
    2020-12-19 08:25

    I had a similar problem with QuerySelectField:

    forms.py :

    class SurgeryForm(Form):
        study = QuerySelectField('Study',
                                 query_factory=StudyGroup.query.all,
                                 get_label='name')
    

    models.py

    class Animal(db.Model):
        study_id = db.Column(db.Integer, db.ForeignKey('study_group.id'))
    
    class StudyGroup(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
        animals = db.relationship('Animal', backref='group', lazy='dynamic')
    

    views.py:

    def do_surgery():
        form = SurgeryForm(request.form)
    
        if form.validate_on_submit():
            a = models.Animal()
            form.populate_obj(a)  # Gather the easy stuff automagically
            #a.group = form.data['study']  #FAILS!
            a.study_id = form.data['study'].id  #WORKS!
    

    It seems that SQLAlchemy (or possibly Flask-SQLAlchemy or Flask-WTF) uses one session to gather the values in the QuerySelectField and another session to create the new Animal object.

    If you try to attach the StudyGroup object to the Animal using the backref (Animal.group) you'll run into this problem (since the objects associated with different sessions). The workaround that I'm using is to set the foreign key (Animal.study_id) directly.

    Clearly I'm a little late to the party with this answer, but I hope it helps someone!

提交回复
热议问题