如何在Flask SQLAlchemy的两个方向上建立与二级backref工作的数据库关系?

时间:2014-09-25 22:12:39

标签: python flask sqlalchemy flask-sqlalchemy has-many

我创建了User模型和Kid模型。在孩子模特中,我有:

parents = db.relationship('User', secondary=kids_users,
                        backref=db.backref('kids', lazy='dynamic'))

辅助表定义如下所示:

kids_users = db.Table('kids_users',
  db.Column('kid_id', db.Integer(), db.ForeignKey('kid.id')),
  db.Column('user_id',db.Integer(), db.ForeignKey('user.id')))

我的User模型不包含与此相关的任何内容,因为此代码可以完成所有操作。

在这种情况下:当我查询some_kid.parents时,它给了我一个很好的数组:

[<User u'someuser@yahoo.com'>]

但是当我查询some_user.kids时,它会回复一些SQL查询:

SELECT kid.id AS kid_id, kid.first_name AS kid_first_name, kid.middle_name AS kid_middle_name, kid.last_name AS kid_last_name, kid.dob AS kid_dob, kid.profile_pic_small AS kid_profile_pic_small, kid.profile_pic_smallish AS kid_profile_pic_smallish, kid.profile_pic_med AS kid_profile_pic_med, kid.profile_pic_large AS kid_profile_pic_large, kid.gender AS kid_gender, kid.current_group AS kid_current_group, kid.status AS kid_status, kid.status_time AS kid_status_time, kid.potty_trained AS kid_potty_trained, kid.pending AS kid_pending, kid.scholarship AS kid_scholarship, kid.govt AS kid_govt, kid.extra_credit AS kid_extra_credit, kid.hold AS kid_hold, kid.school_id AS kid_school_id, kid.between_schedule_id AS kid_between_schedule_id, kid.one_for_all_schedule_id AS kid_one_for_all_schedule_id, kid.hourly_schedule_id AS kid_hourly_schedule_id, kid.calendar_schedule_id AS kid_calendar_schedule_id, kid.code AS kid_code FROM kid, kids_users

我正在尝试使用SomeForm(request.data, obj=some_user)填充表单,并且它永远不会填充子select字段,因为它不会返回数组。

如何让它在两个方向都很好地工作?

1 个答案:

答案 0 :(得分:5)

您使用了lazy='dynamic',这使得该关系返回另一个查询而不是集合。要真正获得该集合,请致电some_kid.parents.all()。动态查询具有方法append(instance)remove(instance)来管理集合。通常,lazy='dynamic'用于非常大的集合,您将在加载任何相关实例之前进一步过滤它。

通常,您只需要lazy='select'(默认值),它指示SQLAlchemy在访问时加载自动select的集合。然后它会表现得像你期望的那样。