On Aug 9, 2011, at 8:38 AM, Wichert Akkerman wrote:

> I have a model where I have articles and images, with a many-to-many relation 
> between them. Since the order of images for an article is important this 
> relation should be ordered from the article site. My naieve implementation 
> looks like this:
> 
> article_images = Table('article_image', BaseObject.metadata,
>    Column('article_id', Integer(),
>        ForeignKey('article.id',
>            onupdate='CASCADE', ondelete='CASCADE'),
>        primary_key=True),
>    Column('image_id', Integer(),
>        ForeignKey('image.id',
>            onupdate='CASCADE', ondelete='CASCADE'),
>        primary_key=True),
>    Column('position', Integer()))
> 
> 
> class Image(BaseObject):
>    __tablename__ = 'image'
>    id = Column(Integer(),
>            Sequence('image_id_seq', optional=True),
>            primary_key=True, autoincrement=True)
>    path = Column(String(128), nullable=False, unique=True)
> 
> 
> class Article(BaseObject):
>    __tablename__ = 'article'
>    id = Column(Integer(),
>            Sequence('article_id_seq', optional=True),
>            primary_key=True, autoincrement=True)
> 
>    #: An ordered list of images for this article. The first image
>    #: is considered to be the *key* image.
>    images = relationship(Image,
>            order_by=[article_images.c.position],
>            secondary=article_images,
>            collection_class=ordering_list('position'))
> 
> 
> Unfortunately this breaks since OrderingList assumes that the position 
> attribute is set on Image instead of the article_images table. From what I 
> can see this is not easily fixed since OrderingList only gets the list of 
> Image instances and doesn't have access to the related article_images row. Is 
> there another way to accomplish this?

Well since the m2m table has a meaningful column on it "position", that means 
you'd go into the association object pattern, optionally though likely with an 
association proxy for Article.images = association_proxy('articleimages', 
'image'), and the ordering_list goes on the "articleimages" relationship from 
Article->ArticleImage.

I've spent all weekend updating docs so lookup "association object" in the 
relationship config chapter.   I also rewrote most of "association proxy".

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" 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/sqlalchemy?hl=en.

Reply via email to