2016-06-28 1 views
0

の関係を持つ子と祖先を再帰的にフェッチし、次のツリーを走査するのに少し役立ちました。 >親 - - >子供 - >サブ Sqlachemy、プロパティとハイブリッドトランスを使用して、

class Category(db.Model): 
    __tablename__ = 'category' 
    id = db.Column(db.Integer, primary_key=True) 
    parent = db.Column(db.Integer, db.ForeignKey('category.id'), nullable=True) 
    name = db.Column(db.String(400), index=True, unique=True) 

    children = db.relationship("Category", cascade='all, delete-orphan', backref=db.backref("child", remote_side=[id])) 
    parents = db.relationship("Category", cascade='all', backref=db.backref("back", remote_side=[id])) 
    entries = db.relationship("Feeds", backref='entry', lazy='dynamic') 


class Feeds(db.Model): 
    __tablename__ = 'feeds' 
    id = db.Column(db.Integer, primary_key=True) 
    category_id = db.Column(db.Integer, db.ForeignKey('category.id')) 
    name = (db.String(400), index=True, unique=True) 

    @property 
    def parents(self): 
     allparents=[] 
     p = self.children 
     while p: 
      allparents.append(p) 
      p = p.children 
     return allparents 

は、私は単純なオブジェクト私は子供が可変のツリーの深さ を持つ取得するためにすべてのツリーをトラバースするにはどうすればよい

catlist = db.session.query(Category).filter_by(id=1).all() 
  1. すなわち祖先を持っています-子?

  2. 私はどのようにサブ子オブジェクトを取得するのですか?

フィードモデルと同じですが、祖先ツリーをどのようにトラバースするのですか、どのように上位祖先ノードのみを取得しますか?

これは、私はあなたが再帰クエリを使用することができますPostgresqlのでエラー

catlist = db.session.query(Category).filter_by(id=1).all() 
for cat in catlist: 
    cat[0].children 



File "/home/afidegnum/PycharmProjects/store/core/model.py", line 45, in children 
    p = self.children 
RuntimeError: maximum recursion depth exceeded 
+0

all_children = Category.get_children_list(1).all() 

をクエリは次のようになりますか? –

+0

@antonio_antuan Postgres – afidegnum

答えて

2

を生成したプロパティオブジェクトから離れてうまく動作しないようであるこれまでにやっていることです。あなたのケースでは、あなたがメソッドを使用することができます

@staticmethod 
def get_parents_list(category_id): 
    beginning_getter = Session.query(Category).\ 
     filter(Category.id == category_id).cte(name='parent_for', recursive=True) 
    with_recursive = beginning_getter.union_all(
     Session.query(Category).filter(Category.id == beginning_getter.c.parent_id) 
     ) 
    return Session.query(with_recursive) 

@staticmethod 
def get_children_list(category_id): 
    beginning_getter = Sesion.query(Category).\ 
      filter(Category.id == category_id).cte(name='children_for', recursive=True) 
    with_recursive = beginning_getter.union_all(
      Session.query(Category).filter(Category.parent_id == beginning_getter.c.id) 
     ) 
    return Session.query(with_recursive) 

が呼び出し:あなたがDBMSを使用してください

WITH RECURSIVE children_for(id, name, parent) AS 
(SELECT id, name, parent 
FROM categories 
WHERE category.id = 1 UNION ALL id, name, parent 
FROM categories, children_for 
WHERE categories.parent = children_for.id) 
SELECT children_for.id, children_for.name, children_for.parent 
FROM children_for;``` 
関連する問題