作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在寻找一种在同一类的两个或多个实例之间以子父关系的形式创建层次结构的方法。
如何像示例中那样从嵌套字典创建此类对象?这可能吗?有没有其他推荐的方法来完成这样的任务?
# -*- coding: utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, exists
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, String
Base = declarative_base()
class Person(Base):
__tablename__ = 'person';
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
parent_id = Column(Integer, ForeignKey('person.id'))
def __init__(self, **kwargs):
self.parent_id = kwargs.get('parent_id', None)
self.name = kwargs.get('name')
self.team = kwargs.get('team', [])
# Is it possible to create more object of this type
# and establish that their parent_id is ID of this object?
def __repr__(self):
return """
ID: {}
Name: {}
ParentID: {}
""".format(self.id, self.name, self.parent_id)
engine = create_engine('sqlite:///db.sqlite3')
Base.metadata.create_all(engine)
connection = engine.connect()
Session = sessionmaker(bind=engine)
session = Session()
alice = {'name' : 'Alice'}
bob = {'name' : 'Bob', 'team' : [alice, ]}
p1 = Person(bob)
session.add(p1)
session.commit()
我了解迭代方法,我首先创建父对象,然后遍历可能的子对象并创建它们。我很好奇是否有一种方法可以在构造函数内部而不是从“外部”使用循环来执行此操作。
最佳答案
试试这个。
#your import statements including "relationship"
Base = declarative_base()
class Person(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
parent_id = Column(Integer, ForeignKey('person.id'))
team = relationship("Person")
def __init__(self, **kwargs):
self.parent_id = kwargs.get('parent_id', None)
self.name = kwargs.get('name')
team_kwargs = kwargs.get('team', [])
for member_kwargs in team_kwargs:
new_person = Person(**member_kwargs)
new_person.parent_id = self.id
self.team.append(new_person)
# Is it possible to create more object of this type
# and establish that their parent_id is ID of this object?
def __repr__(self):
return """
ID: {}
Name: {}
ParentID: {}
""".format(self.id, self.name, self.parent_id)
engine = create_engine('sqlite://')
Base.metadata.create_all(engine)
connection = engine.connect()
Session = sessionmaker(bind=engine)
session = Session()
alice = {'name' : 'Alice'}
joe = {'name' : 'Joe'}
anne = {'name' : 'Anne', 'team': [alice]}
bob = {'name' : 'Bob', 'team' : [anne, joe]}
p1 = Person(**bob)
session.add(p1)
session.commit()
for person in session.query(Person).all():
print(person)
输出:
ID: 1
Name: Bob
ParentID: None
ID: 2
Name: Anne
ParentID: 1
ID: 3
Name: Joe
ParentID: 1
ID: 4
Name: Alice
ParentID: 2
当我在一个已保存的数据库上运行它时,(engine = create_engine('sqlite:///delme.db')
,并多次运行它,它在单个数据库上创建了所有条目添加并提交。
您还可以创建一个单独的“teams”表来存储组长和组员
# your imports and "from sqlalchemy import create_engine, Table"
Base = declarative_base()
teams = Table("teams", Base.metadata,
Column("leader", Integer, ForeignKey("person.id"), primary_key=True),
Column("member", Integer, ForeignKey("person.id"), primary_key=True),
)
class Person(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
team = relationship("Person",
secondary=teams,
primaryjoin=id==teams.c.leader,
secondaryjoin=id==teams.c.member,
)
def __init__(self, **kwargs):
self.name = kwargs.get('name')
team_input = kwargs.get('team', [])
for member in team_input:
new_person = Person(**member)
self.team.append(new_person)
def __repr__(self):
return "ID: {} Name: {}".format(self.id, self.name)
engine = create_engine('sqlite://')
Base.metadata.create_all(engine)
connection = engine.connect()
Session = sessionmaker(bind=engine)
session = Session()
alice = {'name' : 'Alice'}
joe = {'name' : 'Joe'}
anne = {'name' : 'Anne', 'team': [alice]}
bob = {'name' : 'Bob', 'team' : [anne, joe]}
p1 = Person(**bob)
session.add(p1)
session.commit()
for person in session.query(Person).all():
print(person)
for team in session.query(teams).all():
print(team)
输出:
ID: 1 Name: Bob
ID: 2 Name: Anne
ID: 3 Name: Alice
ID: 4 Name: Joe
(1, 2) # anne and joe are on bob's team
(1, 4)
(2, 3) # alice is on anne's team
关于python - 从字典/JSON 构建层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49800747/
我正在尝试将多个水平链接的 Button 和 TextView 垂直链接为 View 集,但仍保持平面 View 层次结构。这是我的初始布局和代码:
到目前为止,我已经在Google BigQuery上训练了几种模型,目前我需要查看模型的外观(即架构,损失函数等)。 有没有办法获取这些信息? 最佳答案 仔细阅读文档后,我可以说该功能尚不存在。我什至
本文实例讲述了PHP实现二叉树深度优先遍历(前序、中序、后序)和广度优先遍历(层次)。分享给大家供大家参考,具体如下: 前言: 深度优先遍历:对每一个可能的分支路径深入到不能再深入为止,而且每个
我是一名优秀的程序员,十分优秀!