title: SQLAlchemy group_concat and duplicates
body: <p>When I try to join a <em>many-to-many</em> table and group it by  the <em>main-id</em> I am getting <strong>duplicates</strong> when I add the second <em>many-to-many</em> table.</p>
  <p>Here is how my models look like:</p>
  <h2>Models</h2>
  <p><strong>user</strong></p>
  <pre><code>class User(UserMixin, db.Model):
      id = db.Column(db.Integer, primary_key=True)
      user_fistName = db.Column(db.String(64))
      ...
  </code></pre>
  <p><strong>student_identifier</strong></p>
  <pre><code>student_identifier = db.Table('student_identifier',
      db.Column('class_id', db.Integer, db.ForeignKey('class.class_id')),
      db.Column('id', db.Integer, db.ForeignKey('user.id'))
  )
  </code></pre>
  <p><strong>class</strong></p>
  <pre><code>class Class(db.Model):
      sqlite_autoincrement=True
      class_id = db.Column(db.Integer, primary_key=True)
      class_name = db.Column(db.String(128), unique=True)
      mm_children = db.relationship('User', secondary=student_identifier, backref=db.backref('classes'))
  </code></pre>
  <p><strong>class_course_identifier</strong></p>
  <pre><code>class_course_identifier = db.Table('class_course_identifier',
      db.Column('course_id', db.Integer, db.ForeignKey('course.course_id')),
      db.Column('class_id', db.Integer, db.ForeignKey('class.class_id'))
  )
  </code></pre>
  <p><strong>database structure</strong></p>
  <p><img src="https://i.stack.imgur.com/1ir9f.png" alt="mydatabase - er diagram" /></p>
  <p>Well I am using SQLAlchemy to select the desired tables with the data I want. with this session.query</p>
  <pre><code>db.session.query(
     Class.class_id,
     Class.class_name,
     func.group_concat(User.user_fistName),
     func.group_concat(Course.course_name)
     ).filter(Class.courses, User.classes).group_by(Class.class_id)
  </code></pre>
  <p>the problem is that I am getting duplicates of both the courses AND names, so if the course has two users it will print the students and the course two times.
  Here is how it is looking:</p>
  <p><strong>wrong view</strong>
  <img src="https://i.stack.imgur.com/WNo9B.png" alt="how it is looking right now" /></p>
  <p>And here is how it should look:</p>
  <p><strong>correct view</strong>
  <img src="https://i.stack.imgur.com/bbtWx.png" alt="the right way to look" /></p>
  <h1>the problem</h1>
  <p>the problem is coming when I am adding the second <em>many-to-many</em> table, for example users/student-identifier. If I remove the line where I &quot;join&quot; it, I am getting the duplicates. Is there anyway to correct this? Or should I use RAW-SQL instead(and if yes, how?)</p>