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 8075591
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T15:02:25+00:00 2026-06-05T15:02:25+00:00

I’ve got a User and Group table with a many to many relationship _usergroup_table

  • 0

I’ve got a User and Group table with a many to many relationship

_usergroup_table = db.Table('usergroup_table', db.metadata,
    db.Column('user_id',  db.Integer, db.ForeignKey('user.id')),
    db.Column('group_id', db.Integer, db.ForeignKey('group.id')))

class User(db.Model):
    """Handles the usernames, passwords and the login status"""
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60), nullable=False, unique=True)

class Group(db.Model):
    """Used for unix-style access control."""
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60), nullable=False)
    users = db.relationship('User', secondary=_usergroup_table,
                            backref='groups')

Now i’d like to add a primary group to the user class. Of course I could just add a group_id column and a relationship to the Group class, but this has drawbacks. I’d like to get all groups when calling User.group, including primary_group. The primary group should always be part of the groups relationship.

Edit:

It seems the way to go is the association object

class User(db.Model, UserMixin):
    """Handles the usernames, passwords and the login status"""
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60), nullable=False, unique=True)

    primary_group = db.relationship(UserGroup,
        primaryjoin="and_(User.id==UserGroup.user_id,UserGroup.primary==True)")

class Group(db.Model):
    """Used for unix-style access control."""
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60), nullable=False)

class UserGroup(db.Model):
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    group_id = db.Column(db.Integer, db.ForeignKey('group.id'))
    active = db.Column(db.Boolean, default=False)

    user = db.relationship(User, backref='groups', primaryjoin=(user_id==User.id))
    group = db.relationship(Group, backref='users', primaryjoin=(group_id==Group.id))

I could simplify this with the AssociationProxy, but how do I force only a single primary group per user?

  • 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-06-05T15:02:27+00:00Added an answer on June 5, 2026 at 3:02 pm

    The group_id approach you originally thought of has several advantages here to the “boolean flag” approach.

    For one thing, it is naturally constrained so that there is only one primary group per user. For another, loading user.primary_group means the ORM can identify this related row by it’s primary key, and can look locally in the identity map for it, or emit a simple SELECT by primary key, instead of emitting a query that has a hard-to-index WHERE clause with a boolean inside of it. Yet another is there’s no need to get into the association object pattern which simplifies the usage of the association table and allows SQLAlchemy to handle loads and updates from/to this table more efficiently.

    Below we use events, including a new version (as of 0.7.7) of @validates that catches “remove” events, to ensure object-level modifications to User.groups and User.primary_group are kept in sync. (If on an older version of 0.7 you can use the attribute “remove” event or the “AttributeExtension.remove” extension method if you’re still on 0.6 or earlier). If you wanted to enforce this at the DB level you could possibly use triggers to verify the integrity you’re looking for:

    from sqlalchemy import *
    from sqlalchemy.orm import *
    from sqlalchemy.ext.declarative import declarative_base
    
    Base= declarative_base()
    
    _usergroup_table = Table('usergroup_table', Base.metadata,
        Column('user_id',  Integer, ForeignKey('user.id')),
        Column('group_id', Integer, ForeignKey('group.id')))
    
    class User(Base):
        __tablename__ = 'user'
        id = Column(Integer, primary_key=True)
        name = Column(String(60), nullable=False, unique=True)
        group_id = Column(Integer, ForeignKey('group.id'), nullable=False)
        primary_group = relationship("Group")
    
        @validates('primary_group')
        def _add_pg(self, key, target):
            self.groups.add(target)
            return target
    
        @validates('groups', include_removes=True)
        def _modify_groups(self, key, target, is_remove):
            if is_remove and target is self.primary_group:
                del self.primary_group
            return target
    
    class Group(Base):
        __tablename__ = 'group'
        id = Column(Integer, primary_key=True)
        name = Column(String(60), nullable=False)
        users = relationship('User', secondary=_usergroup_table,
                                backref=backref('groups', collection_class=set))
    
    e = create_engine("sqlite://", echo=True)
    Base.metadata.create_all(e)
    
    s = Session(e)
    
    g1, g2, g3 = Group(name='g1'), Group(name='g2'), Group(name='g3')
    u1 = User(name='u1', primary_group=g1)
    
    u1.groups.update([g2, g3])
    
    s.add_all([
        g1, g2, g3, u1
    ])
    s.commit()
    
    u1.groups.remove(g1)
    assert u1.primary_group is None
    u1.primary_group = g2
    s.commit()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to count how many characters a certain string has in PHP, but
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I've got a string that has curly quotes in it. I'd like to replace
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I need to clean up various Word 'smart' characters in user input, including but
i got an object with contents of html markup in it, for example: string
I have just tried to save a simple *.rtf file with some websites and
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I would like to count the length of a string with PHP. The string

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.