On Fri, Jan 6, 2012 at 11:38 AM, Mariano Mara <[email protected]>wrote:

> On 05.01.12 23:40, John Anderson wrote:
> > On 01/05/2012 09:07 PM, Mariano Mara wrote:
> > > On 05.01.12 19:20, John Anderson wrote:
> > >>    I have a base schema class and when I subclass it I sometimes want
> to
> > >>    re-order the fields, for instance:
> > >>
> > >>    class ProfileSchema(CSRFSchema):
> > >>        Username = colander.SchemaNode(colander.String())
> > >>
> > >>    class DetailedProfileSchema(ProfileSchema):
> > >>        FirstName = colander.SchemaNode(colander.String())
> > >>
> > >>    I would like first name to be displayed above Username
> > >>
> > >>    Is this possible?
> > > You could define the mapping schema imperatively: in that way you can
> place
> > > the nodes in the order you need each time.
> > >
> > I would like to enjoy the benefits of inheritance if possible.  It will
> > be a maintenance nightmare to redefine the schemas every where just to
> > re-order a couple fields.
> >
>
> Ok, how about this?
>
> $ python
> Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
> [GCC 4.5.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import colander
> >>> class Person(colander.MappingSchema):
> ...     name = colander.SchemaNode(colander.String())
> ...     age =
> colander.SchemaNode(colander.Integer(),validator=colander.Range(0, 200))
> ...
> >>> schema = Person()
> >>> schema.children
> [<colander.SchemaNode object at 3076890668 (named name)>,
> <colander.SchemaNode object at 3076892108 (named age)>]
> >>> f = schema.children.pop(0)
> >>> schema.children.append(f)
> >>> schema.children
> [<colander.SchemaNode object at 3076892108 (named age)>,
> <colander.SchemaNode object at 3076890668 (named name)>]
> >>>
>
>
This works at the instance level, I want to work at the class level so that
I'm not doing extra code whenever I use the schema. But this was what I
wanted, here is how I had to do it:

     def __new__(cls, *args, **kwargs):
        obj = ParentClass.__new__(cls, *args, **kwargs)
        order = {'photo': 1}

        children_to_move=[]

        for index, child in enumerate(obj.children):
            if child.name in order:
                n = obj.children.pop(index)
                children_to_move.append((n, order[child.name]))

        for node in children_to_move:
            obj.children.insert(node[1], node[0])

        return obj

-- 
You received this message because you are subscribed to the Google Groups 
"pylons-discuss" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.

Reply via email to