变形/漏勺HTML中的多对多关系选择字段

时间:2014-08-19 05:21:57

标签: python pyramid deform colander

我正在Pyramid框架中工作并使用Deform包来呈现HTML表单,并给出了漏勺方案。我正在努力解决如何处理具有多对多关系的模式的问题。例如,我的s​​qlalchemy模型如下所示:

class Product(Base):
    """ The SQLAlchemy declarative model class for a Product object. """
    __tablename__ = 'products'

    id = Column(Integer, primary_key=True)
    name = Column(String(80), nullable=False)
    description = Column(String(2000), nullable=False)
    categories = relationship('Category', secondary=product_categories,
                               backref=backref('categories', lazy='dynamic'))


class Category(Base):                                                                                
    """ The SQLAlchemy declarative model class for a Category object. """                            
    __tablename__ = 'categories'

    id = Column(Integer, primary_key=True)                                                                                            
    name = Column(String(80), nullable=False)                                                                                                                                 
    products = relationship('Product', secondary=product_categories,                                 
                               backref=backref('products', lazy='dynamic'))


product_categories = Table('product_categories', Base.metadata,
    Column('products_id', Integer, ForeignKey('products.id')),
    Column('categories_id', Integer, ForeignKey('categories.id'))
)

正如您所看到的,这是一个非常简单的模型,代表了一个产品可以属于一个或多个类别的在线商店。在我的渲染形式中,我想有一个选择多个字段,我可以在其中选择几个不同的类别来放置产品。这是一个简单的漏勺模式:

def get_category_choices():

    all_categories = DBSession.query(Category).all()

    choices = []
    for category in all_categories:
        choices.append((category.id, category.name))

    return choices


class ProductForm(colander.Schema):
    """ The class which constructs a PropertyForm form for add/edit pages. """

    name = colander.SchemaNode(colander.String(), title = "Name",
                               validator=colander.Length(max=80),
                              )

    description = colander.SchemaNode(colander.String(), title="Description",
                                  validator=colander.Length(max=2000),
                                  widget=deform.widget.TextAreaWidget(rows=10, cols=60),
                                 )

    categories = colander.SchemaNode(
                colander.Set(),
                widget=deform.widget.SelectWidget(values=get_category_choices(), multiple=True),
                validator=colander.Length(min=1),
                )

而且,当然,我确实对所有字段进行了正确的渲染,但是,“类别”字段似乎并未与任何字段“绑定”。如果我编辑一个我知道属于两个类别的产品,我希望select字段已经突出显示了这两个类别。进行更改(选择第三项)应导致DB更改,其中product_categories具有给定product_id的三行,每行具有不同的category_id。它可能是TMI,但我也使用类似于this的方法来读/写appstruct。

现在,我已经看到mention(和again)使用Mapping来处理多对多关系字段,例如,但是没有一个如何使用它的可靠示例。

提前感谢任何可以伸出援助之手的人。不胜感激。

1 个答案:

答案 0 :(得分:6)

我出现在这个左侧的场地上,甚至没有为正确的区域提出正确的问题。我真正想要的是在多选漏勺SchemaNode中选择一些默认值。我将问题提交给pylons-discuss Google小组,他们能够帮助我。当我在我的Product类中构建appstruct时,使用'set()',如下所示:

def appstruct(self):
    """ Returns the appstruct model for use with deform. """

    appstruct = {}
    for k in sorted(self.__dict__):
        if k[:4] == "_sa_":
            continue

        appstruct[k] = self.__dict__[k]

    # Special case for the categories
    appstruct['categories'] = set([str(c.id) for c in self.categories])

    return appstruct

然后,我将它(以及appstruct中的其他项目)一起传递给表单,并且正确地呈现HTML,并选择了所有类别。要在提交后应用appstruct,代码最终看起来像:

def apply_appstruct(self, appstruct):
    """ Set the product with appstruct from the submitted form. """

    for kw, arg in appstruct.items():

        if kw == "categories":
            categories = []
            for id in arg:
                categories.append(DBSession.query(Category).filter(Category.id == id).first())
            arg = categories

        setattr(self, kw, arg)

漏勺架构最终看起来像:

def get_category_choices():
    all_categories = DBSession.query(Category).all()
    return [(str(c.id), c.name) for c in all_categories]

categories = get_category_choices()

class ProductForm(colander.Schema):
    """ The class which constructs a ProductForm form for add/edit pages. """

    name = colander.SchemaNode(colander.String(), title = "Name",
                               validator=colander.Length(max=80),
                              )

    description = colander.SchemaNode(colander.String(), title="Description",
                                  validator=colander.Length(max=2000),
                                  widget=deform.widget.TextAreaWidget(rows=10, cols=60),
                                 )

    categories = colander.SchemaNode(
                colander.Set(),
                widget=deform.widget.SelectWidget(
                    values=categories,
                    multiple=True,
                ),
                validator=colander.Length(min=1),
                )

感谢所有看过的人。我道歉,我问的是错误的问题而不是保持简单。 : - )