On May 29, 2014, at 9:46 AM, Jason Wirth <wirth.ja...@gmail.com> wrote:

> I've been learning SQLAlchemy and wanted to model of "Users" where they can 
> add "friends" and any additions populate across all users. I pulled my hair 
> out yesterday because I could get it to work in one direction, but not 
> bi-directionally. This seems like such a simple thing (it's easily done in 
> the Django ORM). 
> 
> The use would be something like this:
> 
> jobs = Person(name='Steve Jobs') 
> woz = Person(name='Steve Wozniak') 
> ive = Person(name='Johnny Ive') 
> 
> jobs.friends = [woz, ive]
> 
> >>> jobs 
> Out[1]: <Person (Steve Jobs)> 
> 
> >>> jobs.friends 
> Out[2]: [<Person (Steve Wozniak)>, <Person (Johnny Ive)>]
> 
> >>> woz.friends 
> Out[3]: [<Person (Steve Jobs)>]
> 
> 
> I found Mike's answer to this problem: 
> 
> - http://www.mail-archive.com/sqlalchemy%40googlegroups.com/msg26262.html
> - 
> http://stackoverflow.com/questions/9116924/how-can-i-achieve-a-self-referencing-many-to-many-relationship-on-the-sqlalchemy

that answer refers to a special relationship "all_friends" which will give you 
friends in both directions.   This is not so much about Django or SQLAlchemy as 
it is about the SQL that's emitted.    When dealing with a many-to-many 
relationship, the relationship between two rows is directional.   If A refers 
to B, we query across the m2m table in one direction, but that won't give us 
all the A for which B refers.

In short I'd be very curious to see what SQL the Django approach emits in order 
for friends to be multi-directional.   It may be INSERTing two M2M rows for 
each friendship to cover both directions, it may be emitting two separate 
SELECT statements for each call to friends, or it may be emitting a UNION 
(unlikely).   But an M2M relationship is not multi-directional by default.   
That Django completely hides from you how it achieves this is IMHO a bad thing. 
  


-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to