我有一个这样的Category对象:
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。我一定漏掉了什么。
发布于 2011-08-01 03:37:53
元组NULL, 'root'是否是唯一的在不同的数据库管理系统中略有不同;这是最近添加到sql标准中的。在大多数情况下,它不是唯一的,毕竟,NULL = NULL不是真的。
您已经要求根元组的id为1,因此可以安全地从父ID中删除nullable=True;然后将根对象设置为它自己的父对象。
https://stackoverflow.com/questions/6891712
复制相似问题