首页 > 解决方案 > 父/子一对多区分 Null 与零子

问题描述

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

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)

标签: pythondatabasedatabase-designsqlalchemy

解决方案


推荐阅读