A colleague of mine submitted a question to StackOverflow ( 
http://stackoverflow.com/questions/5666732/sqlalchemy-self-referential-relationship-not-including-self
 ) which I've been struggling to answer (code given below for those who don't 
want to visit the link).

Given, for example, a Film table and a Countries table, how can you add a 
relationship to the Film mapper that will give you a list of countries that 
have the same film, but which doesn't include the Film itself?

I tried:

primaryjoin=sqlalchemy.and_(
    film_table.c.country_id==film_table.c.country_id,
    film_table.c.id!=film_table.c.id)

but this doesn't work as it doesn't replace one of the `film_table.c.id`s with 
a bindparam.

More generally, in a relationship, how do you force a column reference to be to 
'self' and how does SQLalchemy decide which references are to 'self' and which 
are to the objects it's going to get?

Thanks

Ed

Example code follows:


from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey 
from sqlalchemy.orm import mapper, relationship
metadata = MetaData()
country_table = Table('country', metadata,
    Column('id', String, primary_key=True),
    Column('name', String),
    )
film_table = Table('film', metadata,
    Column('id', Integer, primary_key=True),
    Column('title', String),
    Column('year', Integer),
    Column('country_id', Integer, ForeignKey('country.id'))
    )

class Country(object):
    pass

class Film(object):
    pass

mapper(Country, country_table)

mapper(Film, film_table, 
        properties={
            'country':relationship(
                    Country,
                    backref='films'),
            'same_country_films':relationship(
                    Film,
                    primaryjoin=film_table.c.country_id==\
                                film_table.c.country_id,
                    foreign_keys=[
                        film_table.c.country_id,
                        ]
                    )
             }
    )

-- 
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