How to filter elements that have the same key or value?

Viewed 44

I have this query:

results = db.query(Requests.product, Requests.end_point, func.count(Requests.id)).\
            filter(Requests.user_id == user_id,\
                   Requests.date >= initial_date,\
                   Requests.date <= end_date).\
            group_by(Requests.product, Requests.end_point).order_by(Requests.product).all()

Which returns N (product, endpoints, requests).
Now I need to return this:

{
    "data": {
        "start_date": "date"
        "end_date": "date"
        "requests_by_product": [
            "product": "product name",
            "requests": "total requests",
            "requests_by_endpoint": [
                "endpoint": "endpoint name",
                "requests: "total requests"
            ]
        ]
    }
}

So, I'm trying to get that response through a for loop:

requests_by_endpoint = []
requests_by_product = []
for item in results:
    requests_by_endpoint.append({"endpoint":item[1], "requests":item[2]})
    requests_by_product.append({"product": item[0], "requests":item[2]})

response =  {"data": {"start date": initial_date, "end date": end_date,\
             "requests_by_product": requests_by_product, "requests_by_endpoint": requests_by_endpoint}}

So, of course this is wrong because it's not summing all products requests, just showing one by one. Also, its not filtering the endpoints by products, but just returning a list with all endpoints from all products.

I tried everything, and I can't find a way to sum the requests per products, nor how to filter the endpoints..

I know the 'response' is not formatted correctly, that I can do. I just wrote here the 'simple-er' version.

Well, I found a way to sum the products requests, but I couldn't find a way to use it:

from collections import Counter
    counter = Counter()
    for product in sum_of_all_reqs:
        counter += product
    sorted(counter.items())

Sorry if this is too much to ask, but any help is appreciated!

0 Answers
Related