Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6955301
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T14:43:08+00:00 2026-05-27T14:43:08+00:00

I’m trying to create a social-network like many-to-many mapping in SQLAlchemy. That is I

  • 0

I’m trying to create a social-network like many-to-many mapping in SQLAlchemy. That is I have a Character class and a character_relations cross table to link from Character to Character. Until now this is easy:

character_relationships = Table('character_relationships', Base.metadata,
    Column('me_id', Integer, ForeignKey('characters.id', ondelete=True, onupdate=True), nullable=False, primary_key=True),
    Column('other_id', Integer, ForeignKey('characters.id', ondelete=True, onupdate=True), nullable=False, primary_key=True),
    UniqueConstraint('me_id', 'other_id', name='uix_1')
)

class CharacterRelationship(object):

    def __init__(self, me_id, other_id):
        self.me_id = me_id
        self.other_id = other_id

mapper(CharacterRelationship, character_relationships)

class Character(IdMixin, TimestampMixin, Base):
    __tablename__ = "characters"

    name = Column(Unicode, nullable=False)

    friends = relationship(lambda: Character, secondary=character_relationships, 
             primaryjoin=lambda: Character.id==character_relationships.c.me_id,
             secondaryjoin=lambda: Character.id==character_relationships.c.other_id,
             backref=backref('knows_me')
             )

There are two possible relationships: unilateral and bilateral. That is in the cross table I can have

CharacterRelationship(me_id=1, other_id=2)
CharacterRelationship(me_id=2, other_id=1)

The Character.friends argument as given above is about unilater relationships. How can one add a property/column_property for bilateral relationships?

That is my_character.real_friends contains only entries from CharacterRelationship if the relationship “stands from both sides”.

I know that I could use something like

@property
def real_friends(self):
    return set(my_character.friends) & set(my_character.knows_me)

but this doesn’t translate well to sql, and I would expect a huge speedup doing this set intersection at the database level. But there is even more to achieve!

Even better would be to have a final object like:

character.friends.other_character
character.friends.relationship_type = -1 | 0 | 1

where

  • -1 means I know other unilaterally,
  • 0 bilateral,
  • 1 means other knows me unilaterally

Do you see any reason to put this logic at the database level? If yes, how would you do it?
If know, do you know how to put the simple real_friend bilateral part at the database level?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T14:43:08+00:00Added an answer on May 27, 2026 at 2:43 pm

    For real_friends, you would want to query this at the database level. It should look something like this:

    @property
    def real_friends(self):
        char_rels1 = aliased(CharacterRelationship)
        char_rels2 = aliased(CharacterRelationship)
        return DBSession.query(Character).\
            join(char_rels1, char_rels1.other_id == Character.id).\
            filter(char_rels1.me_id == self.id).\
            join(char_rels2, char_rels2.me_id == Character.id).\
            filter(char_rels2.other_id == self.id).all()
    

    You can of course set this as a relationship.

    For other_character (I’m assuming these are non-mutual friends), I would do a similar query but with an outerjoin.

    For relationship_type, I would do the following while caching knows_person():

    def knows_person(self, person):
        return bool(DBSession.query(CharacterRelationship).\
            filter(CharacterRelationship.me_id == self.id).\
            filter(CharacterRelationship.other_id == person.id).\
            first())
    
    def rel_type(self, person):
        knows = self.knows_person(person)
        known = person.knows_person(self)
        if knows and known:
            return 0
        elif knows:
            return -1
        elif known:
            return 1
        return None
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm trying to create an if statement in PHP that prevents a single post
Basically, what I'm trying to create is a page of div tags, each has
I've got a string that has curly quotes in it. I'd like to replace
I am trying to render a haml file in a javascript response like so:
I have this code to decode numeric html entities to the UTF8 equivalent character.
I am doing a simple coin flipping experiment for class that involves flipping a
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.