[Grok-dev] Example megrok.rdb 'many to many'
Santiago Videla
santiago.videla at gmail.com
Wed Apr 1 22:57:12 EDT 2009
Hey
On Wed, Apr 1, 2009 at 7:39 AM, adevc <f.s.silvestris at gmail.com> wrote:
>
> Hi list,
>
> i am trying a 'many to many' rdb relation in grok with megrok.rdb,
> zope.sqlalchemy.
> But it is going nowhere :)
I found a way to have that kind of relationship. It's more about SQLAlchemy
[1] than megrok.rdb I think (at least "my way")
If we have two models (tables) `Clients` and `Services` and we want the
relation N:N between these tables.
from sqlalchemy import schema, types, orm
from megrok import rdb
#Table to make the many-to-many relation between services and clients
client_services = schema.Table(
"client_services",
metadata,
schema.Column("client_id",
types.Integer,
schema.ForeignKey("clients.id")),
schema.Column('service_id',
types.Integer,
schema.ForeignKey("services.id"))
)
class Client(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("clients")
id = schema.Column(types.Integer)
....
services = orm.relation("Services",
secondary=client_services,
backref="clients")
class Service(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("services")
id = schema.Column(types.Integer)
...
Then, you should be able to write something like:
>>> from megrok import rdb
>>> session = rdb.Session()
>>> ser1 = Service()
>>> ser2 = Service()
>>> session.add(ser1)
>>> session.add(ser2)
>>> session.flush()
>>> c1 = Client()
>>> c2 = Client()
>>> c1.services = [ser1, ser2]
>>> c2.services = [ser1]
>>> session.flush()
If you need to add extra columns in the relation, you may want to take a
look here [2]
Best regards
[1] http://www.sqlalchemy.org/docs/05/mappers.html#many-to-many
[2] http://www.sqlalchemy.org/docs/05/mappers.html#association-pattern
> Is there a grok example for a simple case (N:N) somewhere that one could
> study?
>
> thanks
>
> --
> View this message in context:
> http://www.nabble.com/Example-megrok.rdb-%27many-to-many%27-tp22823822p22823822.html
> Sent from the Grok mailing list archive at Nabble.com.
>
> _______________________________________________
> Grok-dev mailing list
> Grok-dev at zope.org
> http://mail.zope.org/mailman/listinfo/grok-dev
>
--
Santiago Videla
www.revolucionesweb.com.ar
http://www.linkedin.com/in/svidela
Sigue la mata dando de que hablar siempre abajo y a la izquierda donde el
pensamiento que se hace corazón resplandece con la palabra sencilla y
humilde que l at s tod at s somos.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.zope.org/pipermail/grok-dev/attachments/20090401/f2a98f6d/attachment.html
More information about the Grok-dev
mailing list