2011-07-31 6 views
1

私はこのようなカテゴリーのオブジェクトがあります。SQLAlchemyの自己参照PARENT_IDジレンマ

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'), 
     ) 

を私が午前問題は、私はなし「PARENT_ID」で2「ルート」オブジェクトを作成することができだということで、それはそうですUniqueConstraintはNone 'parent_id'には適用されません。理想的には、parent_idがNoneのオブジェクトは1つだけです。私はここで何かを逃しているに違いない。

答えて

3

タプルNULL, 'root'がユニークであるかどうかは、DBMSからDBMSに少し異なります。これはやや最近SQL標準に追加されました。ほとんどの場合、はユニークではありません、結局、NULL = NULLは真ではありません。

既に親タプルのidが1である必要があります。したがって、親IDからnullable = Trueを安全に削除できます。ルートオブジェクトをそれ自身の親に設定するだけです。

+0

引数には影響しませんが、 'NULL = NULL'はfalseでもtrueでもありません。 –

+0

@ypercube:fixed。 null = nullがnullであると書きましたが、最終バージョンでは何とかそれを元に戻しました。 – SingleNegationElimination

+0

ありがとう! Null = Nullは真実ではないので私を捨てた。 – Lloyd