简体   繁体   English

查询 sqlalchemy 并计算不同的结果

[英]Query sqlalchemy and count distinct results

I want to write a query to count how many items a User has organized by Product.title.我想编写一个查询来计算用户按 Product.title 组织了多少项目。

This function gives exactly what I want.这个 function 正是我想要的。 I feel like there is a way I can use func.count to make this into 1 line.我觉得有一种方法可以使用 func.count 将它变成一行。

    def cart(self):
        items = {}
        for product in Product.query.join(Item).filter(Item.user==self):
            item=Item.query.filter(Item.user==self, Item.product==product)
            items[product.title] = {'id': product.id,'count': item.count(), 'cost': product.cost}
        return items

This is my desired return.这是我想要的回报。 I've tried joining Product and Item, but I just get the distinct Product returns with no ability to count.我试过加入产品和项目,但我只是得到了不同的产品退货,无法计数。 Any suggestions?有什么建议么?

    Product.title: count
    Apples: 10
    Bananas: 5
    Hotdogs: 1

Tables:表:

class Item(db.Model):
    __tablename__ = 'item'

    id = db.Column(db.Integer, primary_key=True)

    product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False)
    product = db.relationship("Product")

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship("User")

class Product(db.Model):
    __tablename__ = 'product'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String, nullable=False)

    items = db.relationship('Item', back_populates='product', lazy='dynamic')

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    items = db.relationship('Item', back_populates='user', lazy='dynamic')

I think this query should work as you wish:我认为这个查询应该如你所愿地工作:

query = Product.query.join(Item)
.filter(Item.user==self)
.with_entities(Product.id, Product.cost, Product.title, func.count(Product.id))
.group_by(Product.id, Product.cost, Product.title)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM