如何在SQLAlchemy中的hybrid_property表达式中获取两个查询的总和?

时间:2020-06-17 15:42:25

标签: sqlalchemy flask-sqlalchemy

我正在尝试编写一个混合属性function woocommerce_category_image() { if ( is_product_category() ){ $term = get_queried_object(); // get the WP_Term Object $image_id = get_term_meta( $term->term_id, 'thumbnail_id', true ); if( empty( $image_id ) && $term->parent > 0 ) { $image_id = get_term_meta( $term->parent, 'thumbnail_id', true ); } $image_src = wp_get_attachment_url( $image_id ); // Get the image Url if ( ! empty($image_src) ) { echo '<img src="' . $image_src . '" alt="' . $term->name . '" />'; } } } ,该属性返回两个查询的结果之和。到目前为止,我所有的尝试都失败了。这是一个简化的示例:

expression

我的方法基于此答案the PR author authorized such access when opening their PR,但会导致SQL语法错误:

class House(Model):

    rooms = db.relationship('Room', backref='house', lazy='joined')
    gardens = db.relationship(
        'Garden', backref='house', lazy='joined'
    )

    @hybrid_property
    def total_area(self):
        """Return the sum total of the areas of all rooms and gardens."""
        return sum([_.area for _ in (self.rooms + self.gardens)])

    @total_items.expression
    def total_area(cls):
        """Returns an SQLA expression for querying total_area."""

        total_room_area = (
            select([db.func.sum(Room.area)])
            .where(Room.houseID == cls.id)
        )

        total_garden_area = (
            select([db.func.sum(Garden.area)])
            .where(Garden.houseID == cls.id)
        )

        # This doesn't work 
        return db.cast(total_room_area, db.Numeric) + db.cast(
            total_garden_area, db.Numeric
        )

0 个答案:

没有答案