【问题标题】:How to order by count of many to many relation with Elixir?如何按与 Elixir 的多对多关系计数?
【发布时间】:2012-02-25 14:10:29
【问题描述】:

使用 Elixir 并拥有两个实体——选民和候选人——它们之间存在多对多(如果重要的话,选民可以投票给许多候选人)。想要获得按选民数量排序的候选人名单。有没有办法使用这样的 Elixir 声明来做到这一点?:

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

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

我已阅读 SQLAlchemy ordering by count on a many to many relationship,但希望以更清晰的方式使用 Elixir。我希望,这是可能的。

【问题讨论】:

    标签: python orm sqlalchemy python-elixir


    【解决方案1】:

    我发现在 Elixir 中可以通过多对多关系进行排序的唯一方法是从关系中剔除辅助表并“像往常一样在炼金术中”。大致是这样的:

    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')
    

    【讨论】:

      猜你喜欢
      • 2011-02-18
      • 1970-01-01
      • 2014-05-17
      • 2014-08-25
      • 2017-08-25
      • 2011-10-10
      • 2020-06-25
      • 2011-12-18
      • 2021-12-27
      相关资源
      最近更新 更多