I want to create a function that can print variables for each line as I have already done, but in a more readable way.
date_from = '2018-01-08 00:00:00'
date_to = '2018-01-08 23:59:59'
parent_cat = [14,23,51]
f_categ_id = [24,23,32]
previous = True
previous = '_pre' if previous == True else ''
print("SELECT \n" \
"sum(l.product_uom_qty / u.factor * u2.factor) as product_uom_qty,\n" \
"sum(l.qty * (l.price_unit - (l.discount * l.price_unit / 100)))::double precision AS price_total%s, \n" \
"sum(l.product_uom_qty * l.purchase_price ) as cost_price%s, \n" \
"sum(l.margin) as margin, \n" \
"c.parent_id as parent_id, \n" \
"t.categ_id as categ_id \n" \
"FROM sale_order_line l \n" \
"JOIN sale_order s on (l.order_id=s.id) \n" \
"LEFT JOIN product_product p on (l.product_id=p.id) \n" \
"LEFT JOIN product_template t on (p.product_tmpl_id=t.id) \n" \
"LEFT JOIN product_category c on (c.id=t.categ_id) \n" \
"LEFT JOIN product_uom u on (u.id=l.product_uom) \n" \
"LEFT JOIN product_uom u2 on (u2.id=t.uom_id) \n" \
"WHERE \n" \
"s.date_order >=%s and s.date_order <=%s and t.categ_id in %s and t.categ_id in %s \n"
"GROUP BY \n" \
"t.categ_id , c.parent_id" %(previous, previous, date_from, date_to, tuple(parent_cat), tuple(f_categ_id)))
I would like to know if it is possible to remove the part of
%(previous, previous, date_from, date_to, tuple(parent_cat),
tuple(f_categ_id))
and go adding each of the variables in the corresponding line, for example something like:
"sum(l.product_uom_qty * l.purchase_price ) as cost_price%s, \n" \ % previous
Thank you very much.
You have several ways to improve readability.
In python, a string can be composed on multiple lines and combined with variables (which would be what you want):
Note that I have added
previus
at the end.It can be done better if we group the lines with parentheses, so we forget about having to add a
\
at the end:But it's more elegant than using multiline literals:
To give values to variables, use the method
.format()
instead of the operator%
and assign them by name, something like this: