首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQLAlchemy自引用parent_id dilemna

SQLAlchemy自引用parent_id dilemna
EN

Stack Overflow用户
提问于 2011-08-01 03:19:09
回答 1查看 207关注 0票数 1

我有一个这样的Category对象:

代码语言:javascript
复制
def parent_default(context):
    ''' default parent id if the name is not root '''
    id_ = None
    if context.current_parameters['name'] != u'root' :
        id_ = 1
    return id_


class Category(Base):
    ''' Class representing a product category. '''
    __tablename__ = "CATEGORY"
    id = Column(Integer, primary_key=True)
    name = Column(Unicode(50), nullable=False)
    #self-referential mapper
    parent_id = Column(Integer, ForeignKey('CATEGORY.id'), default=parent_default)
    products = relationship("Product", backref="products")
    parent = relationship('Category', remote_side=[id], backref='sub_categories')

    __table_args__ = (
            UniqueConstraint('parent_id', 'name'),
        )

我遇到的问题是,我能够创建两个没有‘UniqueConstraint _id’的‘根’对象,似乎这个根对象不适用于没有'parent_id‘的根对象。理想情况下,只有一个对象的parent_id为None。我一定漏掉了什么。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-08-01 03:37:53

元组NULL, 'root'是否是唯一的在不同的数据库管理系统中略有不同;这是最近添加到sql标准中的。在大多数情况下,它不是唯一的,毕竟,NULL = NULL不是真的。

您已经要求根元组的id为1,因此可以安全地从父ID中删除nullable=True;然后将根对象设置为它自己的父对象。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6891712

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档