martsberger / django-pivot

A module for pivoting Django Querysets
MIT License
209 stars 16 forks source link

is it possible to remove doublescore for lookup columns? #17

Closed tombohub closed 11 months ago

tombohub commented 3 years ago

for example

stock = pivot(Transaction, 'product__name',
                  'location__name', 'quantity', default=0)

I want response to be {'product_name' : 'Shirt'} instead of { 'product__name' : 'Shirt' }

Speedy1991 commented 3 years ago

You can easily do this in python:

# Write your own converter here
def to_camel_case(snake_str):
  components = snake_str.split("__")
  return components[0] + "".join(x.capitalize() if x else "_" for x in components[1:])

def sanitize_keys(data):
    if isinstance(data, dict):
        return {to_camel_case(k): v for k, v in data.items()}
    if isinstance(data, list):
        return [sanitize_keys(value) for value in data]
    return data

Obviously, you will need to unpack your Query into a list - maybe this could lead to some performance issues (e.g. if you use the pivot/histogram query as a subquery)

€dit: You can simplify the sanitize_keys function if you don't want to sanitize nested keys.

martsberger commented 11 months ago

I think it is maybe a matter of taste to have the double underscore or the single underscore. As noted by Speedy1991, you can change this in your code if you like. The double underscore is a standard Django notation for a model join. I don't think it's worth supporting both versions in this package.