Python 在sqlalchemy中插入具有一对多关系的新记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16433338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:36:36  来源:igfitidea点击:

Inserting new records with one-to-many relationship in sqlalchemy

pythonsqlalchemyforeign-keysrelationshipflask-sqlalchemy

提问by wanderlust

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

我正在关注关于一对多关系声明模型的flask-sqlalchemy教程。示例代码如下:

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'))

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.

现在我想知道如何使用这种模型将新记录插入到数据库中。我假设我需要一个构造函数init,但我很难理解它应该如何实现和使用。对我来说,这里的主要问题是 Person 依赖于 Address 并且 Address 有 ForeignKey 到 Person,所以它应该提前知道 Person。

Plase help me to understand how it should be performed.

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

Thank you in advance.

先感谢您。

采纳答案by DazWorrall

You dont need to write a constructor, you can either treat the addressesproperty on a Personinstance as a list:

您不需要编写构造函数,您可以将实例addresses上的属性Person视为列表:

a = Address(email='[email protected]')
p = Person(name='foo')
p.addresses.append(a)

Or you can pass a list of addresses to the Personconstructor

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

a = Address(email='[email protected]')
p = Person(name='foo', addresses=[a])

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

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

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='[email protected]').count() # 1

回答by padfoot27

The most important thing while looking into this model is to understand the fact that this model has a one to many relationship, i.e. one Person has more than one address and we will store those addresses in a list in our case.

研究这个模型时最重要的事情是理解这个模型有一对多关系这一事实,即一个 Person 有多个地址,我们将在我们的案例中将这些地址存储在一个列表中。

So, the Person class with its initwill look something like this.

因此,带有init的 Person 类将如下所示。

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')

    def __init__(self,id,name,addresses = []):
        self.id = id
        self.name = name
        self.addresses = addresses

So this Person class will be expecting an id, a name and a list that contains objects of type Address. I have kept that the default value to be an empty list.

因此,这个 Person 类将需要一个 id、一个名称和一个包含 Address 类型对象的列表。我将默认值保留为空列表。

Hope it helps. :)

希望能帮助到你。:)