sqlalchemy.cast.op

Here are the examples of the python api sqlalchemy.cast.op taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1 Examples 7

0 Source : election_compound.py
with MIT License
from OneGov

    def get_list_results(self, limit=None, names=None):
        """ Returns the aggregated number of mandates and voters count of all
        the lists.

        These results are only comparable for elections using the Doppelter
        Pukelsheim system and are therefore only provided in this case.

        Sorts the results by number of mandates if the election is completed,
        by voters count else.

        """

        if not self.pukelsheim:
            return []

        order_by = 'voters_count'
        if self.completed:
            order_by = 'number_of_mandates'

        session = object_session(self)

        # Query number of mandates
        mandates = session.query(
            List.name.label('name'),
            func.sum(List.number_of_mandates).label('number_of_mandates'),
            literal_column('0').label('voters_count')
        )
        mandates = mandates.join(ElectionCompound.associations)
        mandates = mandates.filter(ElectionCompound.id == self.id)
        if names:
            mandates = mandates.filter(List.name.in_(names))
        mandates = mandates.join(Election, List)
        mandates = mandates.group_by(List.name)

        # Query voters counts
        voters_counts = session.query(
            List.name.label('name'),
            literal_column('0').label('number_of_mandates'),
            func.sum(
                func.round(
                    cast(ListResult.votes, Numeric).op('/')(
                        cast(Election.number_of_mandates, Numeric)
                    )
                )
            ).label('voters_count'),
        )
        voters_counts = voters_counts.join(ElectionCompound.associations)
        voters_counts = voters_counts.filter(ElectionCompound.id == self.id)
        if names:
            voters_counts = voters_counts.filter(List.name.in_(names))
        voters_counts = voters_counts.join(Election, List, ListResult)
        voters_counts = voters_counts.group_by(List.name)

        # Combine
        union = mandates.union_all(voters_counts).subquery('union')
        query = session.query(
            union.c.name.label('name'),
            cast(func.sum(union.c.number_of_mandates), Integer).label(
                'number_of_mandates'
            ),
            cast(func.sum(union.c.voters_count), Integer).label(
                'voters_count'
            )
        )
        query = query.group_by(union.c.name)
        query = query.order_by(desc(order_by), union.c.name)
        if limit and limit > 0:
            query = query.limit(limit)
        return query.all()

    #: may be used to store a link related to this election
    related_link = meta_property('related_link')