Question

Use Elixir and have two entities -- Voter and Candidate -- with many to many between them(voter can vote for many candidates if it matters). Want to get list of Candidate's sorted by amount of voters. Is there any way to do it using such Elixir's declaration?:

class Voter(Entity):
    votes = ManyToMany('Candidate')

class Candidate(Entity):
    voters = ManyToOne('Voter')

I've read SQLAlchemy ordering by count on a many to many relationship but want to do it in a clearer way with Elixir. I hope, it's possible.

Was it helpful?

Solution

Only way i've found it's possible to order by many-to-many relation in Elixir is to winkle out secondary table from relation and do "just like as usual in alchemy". Roughly something like this:

secondr_table = Candidate._descriptor.find_relationship('voters').secondary_table
cands_by_rank = (
    session.query(
        Candidate.id,
        func.count(secondr_table.c.candidate_id).label('total')
    )
    .join(secondr_table)
    .group_by(Candidate)
    .order_by('total DESC')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top