I have a SQLAlchemy model like this:
class Group(Base):
__tablename__ = 'groups'
id = Column(Integer, primary_key = True, ca_include = True)
name = Column(String, ca_include = True)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key = True, ca_include = True)
name = Column(String, ca_include = True)
group_id = Column(Integer, ForeignKey('groups.id'), nullable = True, ca_include = True)
group = relationship('Group', ca_include = True)
The form library I used is deform. I installed ColanderAlchemy to convert the model definition into Colander Schema automatically:
form = deform.Form(SQLAlchemyMapping(Group), use_ajax = True)
And I can do form.render() to get a empty form. But how to fill this empty form with a record? I tried:
group = Group.get(1)
form.render(group)
But failed. I also followed this blog but it can only convert a single record into colander's format but no relationship would be converted. So... is there anyway for me to convert the SQLAlchemy record into Colander record?
You'll need to utilise the dictify
method associated with your given SQLAlchemyMapping schema object to convert a given model instance into an appstruct acceptable for rendering your Deform form.
So, using your example model, this is what you might do:
schema = SQLAlchemyMapping(Group)
form = deform.Form(schema, use_ajax=True)
my_group = Group(id=1, name='Foobar') #or query for an instance etc
appstruct = schema.dictify(my_group)
form.render(appstruct)
Since ColanderAlchemy is very much cutting edge at this stage, your mileage will likely vary in newer versions (the above was written for version 0.1), especially as it is being substantially rewritten to remove the need for custom columns and relationship types in version 0.2. I've noticed that there were issues with the the current ColanderAlchemy 0.1b6 release - especially with regards to the mapping of relationships.
Consult the documentation at http://colanderalchemy.rtfd.org/ for details on the latest version.