父母/孩子一对多地区分零孩子与零孩子

时间:2018-11-30 17:12:05

标签: python database database-design sqlalchemy

我与父母的关系如下。我希望能够区分空子级(例如,尚不知道的信息)与零子级。这是我目前正在采用的方法。它有效,但似乎有点麻烦。有没有更好的方法可以解决这个问题?

from sqlalchemy import Column, Integer, ForeignKey, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship


Base = declarative_base()
engine = create_engine('sqlite:///')


class Parent(Base):
    __tablename__ = 'parent'

    id = Column(Integer, primary_key=True)

    children = relationship('Child', uselist=False)


class Child(Base):
    __tablename__ = 'child'

    id = Column(Integer, ForeignKey('parent.id'), primary_key=True)

    child_items = relationship('ChildItem')

class ChildItem(Base):
    __tablename__ = 'childitems'

    id = Column(Integer, ForeignKey('child.id'), primary_key=True)

Base.metadata.create_all(engine)
p = Parent()
assert(p.children is None)  # Would like to be able to do something like this.

c = Child()
c.child_items.append(ChildItem())
p.children = c

assert(p.children is not None)

0 个答案:

没有答案