在sqlalchemy中插入具有一对多关系的新记录 [英] Inserting new records with one-to-many relationship in sqlalchemy

查看:54
本文介绍了在sqlalchemy中插入具有一对多关系的新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在跟踪声明模型上的flask-sqlalchemy教程,该教程具有一对多关系.示例代码如下:

I'm following the flask-sqlalchemy tutorial on declaring models regarding one-to-many relationship. The example code is as follows:

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    addresses = db.relationship('Address', backref='person',
                                lazy='dynamic')

class Address(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(50))
    person_id = db.Column(db.Integer, db.ForeignKey('person.id'))

现在,我想知道如何使用这种模型将新记录插入数据库.我假设我需要一个构造器 init ,但是我很难理解应该如何实现和使用它.对我而言,这里的主要问题是Person依赖于Address,而Address具有对该Person的ForeignKey,因此它应该提前了解Person.

Now I'm wondering how to insert new records into DB using such model. I assume I need a constructor init, but I have difficulties to understand how it should be implemented and used. The main problem for me here is that Person depends on Address and Address has ForeignKey to Person, so it should know about the Person in advance.

请帮助我了解应该如何执行.

Plase help me to understand how it should be performed.

谢谢.

推荐答案

您不需要编写构造函数,可以在 Person 实例上使用 addresses 属性作为列表:

You dont need to write a constructor, you can either treat the addresses property on a Person instance as a list:

a = Address(email='foo@bar.com')
p = Person(name='foo')
p.addresses.append(a)

或者您可以将地址列表传递给 Person 构造函数

Or you can pass a list of addresses to the Person constructor

a = Address(email='foo@bar.com')
p = Person(name='foo', addresses=[a])

无论哪种情况,您都可以像下面这样访问 Person 实例上的地址:

In either case you can then access the addresses on your Person instance like so:

db.session.add(p)
db.session.add(a)
db.session.commit()
print p.addresses.count() # 1
print p.addresses[0] # <Address object at 0x10c098ed0>
print p.addresses.filter_by(email='foo@bar.com').count() # 1

这篇关于在sqlalchemy中插入具有一对多关系的新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆