Django Non-Rel: QuerySet is always empty, even though objects exist - django-nonrel

filter() and all() not working on django-nonrel
>>> Item.objects.get(display_name='Test Item')
<Item: Test Item>
>>> Item.objects.all()
[]
>>> Item.objects.get(display_name='Test Item')
<Item: Test Item>
>>> Item.objects.filter(display_name='Test Item')
[]
>>>
On the following model:
class Item(models.Model):
item_id = models.AutoField(
primary_key = True,
db_column = 'id'
)
menu = models.ForeignKey(
Menu,
verbose_name = l('Menu'),
related_name = 'items',
db_column = 'menu_id'
)
display_name = models.NameField(
db_column = 'display_name'
)
description = models.DescriptionField(
db_column = 'description'
)
url = models.CharField(
max_length = 255,
verbose_name = l('Path'),
db_column = 'url'
)
#/////////////////////////////////////////////////////////////////////
#//// Flags
#/////////////////////////////////////////////////////////////////////
external = models.BooleanField(
editable = False,
default = False,
db_column = 'external'
)
new_window = models.BooleanField(
verbose_name = l('Open in new window'),
default = False,
db_column = 'new_window'
)
enabled = models.EnabledField(
db_column = 'is_enabled'
)
expanded = models.BooleanField(
verbose_name = l('Expanded by default'),
editable = False, # Will be implemented in future versions.
default = False,
db_column = 'is_expanded'
)
collapsible = models.BooleanField(
verbose_name = l('Collapsible'),
help_text = l('If this item has children, indicates if they may be collapsed'),
db_column = 'is_collapsible'
)
#/////////////////////////////////////////////////////////////////////
#//// Item tree
#/////////////////////////////////////////////////////////////////////
parent = models.ForeignKey(
'self',
verbose_name = l('Parent'),
related_name = 'children',
blank = True,
null = True,
db_column = 'parent_id'
)
has_children = models.BooleanField(
editable = False,
default = False,
db_column = 'has_children'
)
depth = models.PositiveIntegerField(
editable = False,
default = 1,
db_column = 'depth'
)
weight = models.IntegerField(
verbose_name = l('Weight'),
default = 0,
db_column = 'weight'
)
#/////////////////////////////////////////////////////////////////////
#//// HTML properties
#/////////////////////////////////////////////////////////////////////
id = models.CharField(
max_length = 255,
verbose_name = l('Id'),
help_text = l('By default, the rendered link id will be in the format [item.name]-[item.pk]. Use this field to override'),
default = '',
blank = True,
db_column = 'link_id'
)
cls = models.CharField(
max_length = 255,
verbose_name = l('Class'),
help_text = l('By default, the rendered link class will be in the format [menu.name]. Use this field to append extra classes.'),
default = '',
blank = True,
db_column = 'class'
)
title = models.CharField(
max_length = 255,
verbose_name = l('Title'),
help_text = l('By default, the rendered link title will be item.name. Use this field to override.'),
default = '',
blank = True,
db_column = 'title'
)
target = models.CharField(
max_length = 255,
verbose_name = l('Target'),
blank = True,
default = '',
db_column = 'target'
)
rel = models.CharField(
max_length = 255,
verbose_name = l('Rel'),
blank = True,
default = '',
db_column = 'rel'
)
class Meta:
db_table = 'menu_item'
verbose_name = l('Menu Item')
verbose_name_plural = l('Menu Items')
ordering = ['menu','parent','weight']
QuerySets like filter() and all() on Django-Nonrel keep returning empty, even though objects exists in the database. get() works fine.
I've also tried removing the meta attributes, but to no avail.

The problem is that class Meta: ordering = ['menu','parent','weight'].
This results in "INNER JOIN" statement that django-norel does not support it or implement it yet.

Related

How to increase the size of the text inside the red circle of the cor plot?

How to increase the size of the text inside the red circle of the cor plot?
Used code:
par(mar=c(1,1,1,1))
pairs.panels(data,
method = "pearson",
hist.col = "#00AFBB",
density = TRUE,
ellipses = TRUE,
pch = 21,
cex = 1.5,
cex.axis = 1.8,
lwd = 2,
rug = TRUE,
stars = TRUE
)
Finally, I got the answer and i.e. to add the argument cex.labels = 2.5,
the final code is
library(psych)
par(mar=c(1,1,1,1))
pairs.panels(data,
method = "pearson",
hist.col = "#00AFBB",
density = TRUE,
ellipses = TRUE,
pch = 21,
cex = 1.5,
cex.axis = 1.8,
cex.labels = 2.5,
lwd = 2,
rug = TRUE,
stars = TRUE
)

Add lines to stock picking move lines

In my method, I delete lines from stock.pickings and want to add different lines from my model. but i get an error AttributeError: 'stock.move' object has no attribute 'get'
#api.multi
def _action_procurement_create(self):
res = super(SaleOrderLine, self)._action_procurement_create()
order_line_bom = self.env['sale.order.line.bom'].search([('sale_order_line_id', '=', self.id )])
stock_move_lines = self.env['stock.move']
created_stock_move_lines = self.env['stock.move']
vals = {}
for order in self.order_id:
if self.product_id.bom_ids:
order.picking_ids.move_lines.state = 'draft'
for move_line in order.picking_ids.move_lines:
move_line.unlink()
for bom_line in order_line_bom:
vals['product_id'] = bom_line.product_id.id,
vals['product_uom'] = 1,
vals['location_id'] = 1,
vals['name'] = bom_line.product_id.name,
vals['location_dest_id'] = 1,
created_stock_move_lines += stock_move_lines.create(vals)
order.create(stock_move_lines)
You have defined:
stock_move_lines = self.env['stock.move']
Then you try to pass it to create method:
order.create(stock_move_lines)
As documented in model.py
:param dict vals:
values for the model's fields, as a dictionary::
{'field_name': field_value, ...}
see :meth:`~.write` for details
Please try may it's help you :
#api.multi
def _action_procurement_create(self):
res = super(SaleOrderLine, self)._action_procurement_create()
order_line_bom = self.env['sale.order.line.bom'].search([('sale_order_line_id', '=', self.id )])
stock_move_lines = self.env['stock.move']
created_stock_move_lines = self.env['stock.move']
vals = {}
for order in self.order_id:
if self.product_id.bom_ids:
order.picking_ids.move_lines.state = 'draft'
for move_line in order.picking_ids.move_lines:
move_line.unlink()
for bom_line in order_line_bom:
vals = {
'product_id': bom_line.product_id.id,
'product_uom': 1,
'location_id': 1,
'name': bom_line.product_id.name,
'location_dest_id': 1,
}
created_stock_move_lines += stock_move_lines.create(vals)
order.create(stock_move_lines)

How can the edge colors of individual matplotlib histograms be set?

I've got a rough and ready function that can be used to compare two sets of values using histograms:
I want to set the individual edge colors of each of the histograms in the top plot (much as how I set the individual sets of values used for each histogram). How could this be done?
import os
import datavision
import matplotlib.pyplot
import numpy
import shijian
def main():
a = numpy.random.normal(2, 2, size = 120)
b = numpy.random.normal(2, 2, size = 120)
save_histogram_comparison_matplotlib(
values_1 = a,
values_2 = b,
label_1 = "a",
label_2 = "b",
normalize = True,
label_ratio_x = "measurement",
label_y = "",
title = "comparison of a and b",
filename = "histogram_comparison_1.png"
)
def save_histogram_comparison_matplotlib(
values_1 = None,
values_2 = None,
filename = None,
directory = ".",
number_of_bins = None,
normalize = True,
label_x = "",
label_y = None,
label_ratio_x = None,
label_ratio_y = "ratio",
title = "comparison",
label_1 = "1",
label_2 = "2",
overwrite = True,
LaTeX = False,
#aspect = None,
font_size = 20,
color_1 = "#3861AA",
color_2 = "#00FF00",
color_3 = "#7FDADC",
color_edge_1 = "#3861AA", # |<---------- insert magic for these
color_edge_2 = "#00FF00", # |
alpha = 0.5,
width_line = 1
):
matplotlib.pyplot.ioff()
if LaTeX is True:
matplotlib.pyplot.rc("text", usetex = True)
matplotlib.pyplot.rc("font", family = "serif")
if number_of_bins is None:
number_of_bins_1 = datavision.propose_number_of_bins(values_1)
number_of_bins_2 = datavision.propose_number_of_bins(values_2)
number_of_bins = int((number_of_bins_1 + number_of_bins_2) / 2)
if filename is None:
if title is None:
filename = "histogram_comparison.png"
else:
filename = shijian.propose_filename(
filename = title + ".png",
overwrite = overwrite
)
else:
filename = shijian.propose_filename(
filename = filename,
overwrite = overwrite
)
values = []
values.append(values_1)
values.append(values_2)
bar_width = 0.8
figure, (axis_1, axis_2) = matplotlib.pyplot.subplots(
nrows = 2,
gridspec_kw = {"height_ratios": (2, 1)}
)
ns, bins, patches = axis_1.hist(
values,
color = [
color_1,
color_2
],
normed = normalize,
histtype = "stepfilled",
bins = number_of_bins,
alpha = alpha,
label = [label_1, label_2],
rwidth = bar_width,
linewidth = width_line,
#edgecolor = [color_edge_1, color_edge_2] <---------- magic here? dunno
)
axis_1.legend(
loc = "best"
)
bars = axis_2.bar(
bins[:-1],
ns[0] / ns[1],
alpha = 1,
linewidth = 0, #width_line
width = bins[1] - bins[0]
)
for bar in bars:
bar.set_color(color_3)
axis_1.set_xlabel(label_x, fontsize = font_size)
axis_1.set_ylabel(label_y, fontsize = font_size)
axis_2.set_xlabel(label_ratio_x, fontsize = font_size)
axis_2.set_ylabel(label_ratio_y, fontsize = font_size)
#axis_1.xticks(fontsize = font_size)
#axis_1.yticks(fontsize = font_size)
#axis_2.xticks(fontsize = font_size)
#axis_2.yticks(fontsize = font_size)
matplotlib.pyplot.suptitle(title, fontsize = font_size)
if not os.path.exists(directory):
os.makedirs(directory)
#if aspect is None:
# matplotlib.pyplot.axes().set_aspect(
# 1 / matplotlib.pyplot.axes().get_data_ratio()
# )
#else:
# matplotlib.pyplot.axes().set_aspect(aspect)
figure.tight_layout()
matplotlib.pyplot.subplots_adjust(top = 0.9)
matplotlib.pyplot.savefig(
directory + "/" + filename,
dpi = 700
)
matplotlib.pyplot.close()
if __name__ == "__main__":
main()
You may simply plot two different histograms but share the bins.
import numpy as np; np.random.seed(3)
import matplotlib.pyplot as plt
a = np.random.normal(size=(89,2))
kws = dict(histtype= "stepfilled",alpha= 0.5, linewidth = 2)
hist, edges,_ = plt.hist(a[:,0], bins = 6,color="lightseagreen", label = "A", edgecolor="k", **kws)
plt.hist(a[:,1], bins = edges,color="gold", label = "B", edgecolor="crimson", **kws)
plt.show()
Use the lists of Patches objects returned by the hist() function.
In your case, you have two datasets, so your variable patches will be a list containing two lists, each with the Patches objects used to draw the bars on your plot.
You can easily set the properties on all of these objects using the setp() function. For example:
a = np.random.normal(size=(100,))
b = np.random.normal(size=(100,))
c,d,e = plt.hist([a,b], color=['r','g'])
plt.setp(e[0], edgecolor='k', lw=2)
plt.setp(e[1], edgecolor='b', lw=3)

Insert list register with onchange (Odoo)

class base(models.Model):
_name = 'base'
name = fields.Char("Name")
c_id = fields.Many2one('base.ch')
class base_ch(models.Model):
_name = 'base.ch'
name = fields.Char("Name")
q_ids = fields.One2many("base.q","c_id")
class base_q(models.Model):
_name = "base.q"
name = fields.Char("Name")
c_id = fields.Many2one('base.ch',"Basec")
class base_h(models.Model):
_name = "base.h"
name = fields.Char("Name")
select = fields.Selection([('a', 'A'), ('b', 'B')], "select")
desc = fields.Char("Desc")
I have these classes and I want to add in the base class a field of the base_h class in tree view format.
I need to do an onchange function in the base class that when choosing c_id modify the name field of the added field of the base_h class with the records of c_id.q_ids
I tried:
#api.onchange('ch_id')
def onchange_ch(self):
if self.ch_id.q_ids:
self.one2manyfield.name = [(6, 0, self.ch_id.q_ids)]
#also with-> self.one2manyfield = [(6, 0, self.ch_id.q_ids)]
But it does not work
(6, 0, [IDs]) will take list of ids.
Try with following code.
#api.onchange('ch_id')
def onchange_ch(self):
if self.ch_id and self.ch_id.q_ids:
one2manyfield = [(6, 0, self.cht_id.q_ids.ids)]
This is the function that works
#api.onchange('ch_id')
def onch_ch(self):
valors = []
for r in self.ch_id.q_ids:
register = {'name': r.name}
valors.append(register)
self.one2manyfield = valors

How can i generate xls report in odoo

I want to generate my own excel report using Excel report engine in odoo 8. someone please send me a simple excel report sample or any helping URL. I'll be very thankful to you ....
Here is a simple piece of code. There is really a lot of examples on the internet with good explanations. I suggest you go through the code in detail to see how it works (by the way I have copied the code also from somewhere - I cannot remember where. Also have a look at the examples here:https://github.com/OCA/reporting-engine/tree/8.0
The version 8 branch also have a number of examples.
You can add columns by editing the "my_change" variable.
from openerp.osv import orm
from openerp.addons.report_xls.utils import rowcol_to_cell, _render
from openerp.tools.translate import _
class account_move_line(orm.Model):
_inherit = 'abc.salesforecast'
# override list in custom module to add/drop columns or change order
def _report_xls_fields(self, cr, uid, context=None):
return [
'contract', 'proposal', 'description',
#'amount_currency', 'currency_name',
]
# Change/Add Template entries
def _report_xls_template(self, cr, uid, context=None):
"""
Template updates, e.g.
my_change = {
'move':{
'header': [1, 20, 'text', _('My Move Title')],
'lines': [1, 0, 'text', _render("line.move_id.name or ''")],
'totals': [1, 0, 'text', None]},
}
return my_change
"""
return {}
The code for the parser is as follows.
import xlwt
import time
from datetime import datetime
from openerp.osv import orm
from openerp.report import report_sxw
from openerp.addons.report_xls.report_xls import report_xls
from openerp.addons.report_xls.utils import rowcol_to_cell, _render
from openerp.tools.translate import translate, _
from openerp import pooler
import logging
_logger = logging.getLogger(__name__)
class contract_sales_forecast_xls_parser(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(contract_sales_forecast_xls_parser, self).__init__(cr, uid, name, context=context)
forecast_obj = self.pool.get('msr.salesforecast')
self.context = context
wanted_list = forecast_obj._report_xls_fields(cr, uid, context)
template_changes = forecast_obj._report_xls_template(cr, uid, context)
self.localcontext.update({
'datetime': datetime,
'wanted_list': wanted_list,
'template_changes': template_changes,
'_': self._,
})
def _(self, src):
lang = self.context.get('lang', 'en_US')
return translate(self.cr, _ir_translation_name, 'report', lang, src) or src
class contract_sales_forecast_xls(report_xls):
def __init__(self, name, table, rml=False, parser=False, header=True, store=False):
super(contract_sales_forecast_xls, self).__init__(name, table, rml, parser, header, store)
# Cell Styles
_xs = self.xls_styles
# header
rh_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
self.rh_cell_style = xlwt.easyxf(rh_cell_format)
self.rh_cell_style_center = xlwt.easyxf(rh_cell_format + _xs['center'])
self.rh_cell_style_right = xlwt.easyxf(rh_cell_format + _xs['right'])
# lines
aml_cell_format = _xs['borders_all']
self.aml_cell_style = xlwt.easyxf(aml_cell_format)
self.aml_cell_style_center = xlwt.easyxf(aml_cell_format + _xs['center'])
self.aml_cell_style_date = xlwt.easyxf(aml_cell_format + _xs['left'], num_format_str = report_xls.date_format)
self.aml_cell_style_decimal = xlwt.easyxf(aml_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
# totals
rt_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
self.rt_cell_style = xlwt.easyxf(rt_cell_format)
self.rt_cell_style_right = xlwt.easyxf(rt_cell_format + _xs['right'])
self.rt_cell_style_decimal = xlwt.easyxf(rt_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
# XLS Template
self.col_specs_template = {
'contract':{
'header': [1, 20, 'text', _render("_('Contract Number')")],
'lines': [1, 0, 'text', _render("msr_contract_id or ''")],
'totals': [1, 0, 'text', None]},
'proposal':{
'header': [1, 42, 'text', _render("_('Proposal Number')")],
'lines': [1, 0, 'text', _render("msr_proposal or ''")],
'totals': [1, 0, 'text', None]},
'description':{
'header': [1, 42, 'text', _render("_('Description')")],
'lines': [1, 0, 'text', _render("name or ''")],
'totals': [1, 0, 'text', None]},
}
def generate_xls_report(self, _p, _xs, data, objects, wb):
wanted_list = _p.wanted_list
self.col_specs_template.update(_p.template_changes)
_ = _p._
#report_name = objects[0]._description or objects[0]._name
report_name = _("Sales forecast from current contracts")
ws = wb.add_sheet(report_name[:31])
ws.panes_frozen = True
ws.remove_splits = True
ws.portrait = 0 # Landscape
ws.fit_width_to_pages = 1
row_pos = 0
# set print header/footer
ws.header_str = self.xls_headers['standard']
ws.footer_str = self.xls_footers['standard']
# Title
cell_style = xlwt.easyxf(_xs['xls_title'])
c_specs = [
('report_name', 1, 0, 'text', report_name),
]
row_data = self.xls_row_template(c_specs, ['report_name'])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style)
row_pos += 1
# Column headers
c_specs = map(lambda x: self.render(x, self.col_specs_template, 'header', render_space={'_': _p._}), wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.rh_cell_style, set_column_size=True)
ws.set_horz_split_pos(row_pos)
# account move lines
for line in objects:
c_specs = map(lambda x: self.render(x, self.col_specs_template, 'lines'), wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.aml_cell_style)
# Totals
contract_sales_forecast_xls('report.contract.sales.forecast.xls',
'abc.salesforecast',
parser="contract_sales_forecast_xls_parser")
The xml file will look as follows to setup the necessary actions etc.
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<record id="action_contract_sales_forecast_xls" model="ir.actions.report.xml">
<field name="name">Export Selected Lines To Excel</field>
<field name="model">abc.salesforecast</field>
<field name="type">ir.actions.report.xml</field>
<field name="report_name">contract.sales.forecast.xls</field>
<field name="report_type">xls</field>
<field name="auto" eval="False"/>
</record>
<record model="ir.values" id="contract_sales_forecast_xls_values">
<field name="name">Export Selected Lines</field>
<field name="key2">client_action_multi</field>
<field name="value" eval="'ir.actions.report.xml,' +str(ref('action_contract_sales_forecast_xls'))" />
<field name="model">abc.salesforecast</field>
</record>
</data>
</openerp>
A second example. First the xml to create a button. This is only an extract.
<form string = "Contract Search Wizard" version="7.0">
<sheet>
<group>
<button icon="gtk-ok" name="print_contract_list" string="Print Contract List" type="object" />
<button icon="gtk-ok" name="export_contract_product" string="Export Contract vs. Product Pivot Table" type="object" />
<button icon="gtk-ok" name="export_contract_country" string="Export Contract vs. Country Pivot Table" type="object" />
<button icon="gtk-cancel" special="cancel" string="Cancel" />
</group>
</sheet>
</form>
The below code is a wizard with several buttons. I removed some code to save space. The report is activated from a button:
class abc_contract_search_wizard(osv.osv):
def _prd_report_xls_fields(self, cr, uid, context=None):
SQLstring = "SELECT abc_product_list.name FROM abc_product_list;"
cr.execute(SQLstring)
tbl_products = cr.dictfetchall()
header_list=['contract_id','contract_name','exclusive']
for t in tbl_products:
header_list.append(t['name'])
return header_list
# Change/Add Template entries
def _prd_report_xls_template(self, cr, uid, context=None):
"""
Template updates, e.g.
my_change = {
'move':{
'header': [1, 20, 'text', _('My Move Title')],
'lines': [1, 0, 'text', _render("line.move_id.name or ''")],
'totals': [1, 0, 'text', None]},
}
return my_change
"""
SQLstring = "SELECT abc_product_list.name FROM abc_product_list;"
cr.execute(SQLstring)
tbl_products = cr.dictfetchall()
abc_tmpl = {
'contract_id':
{
'header':[1,20, 'text', _render("_('Contract ID')")],
'lines':[1,0, 'text', _render("line.abc_contract_id.name or ''")],
'totals':[1, 0, 'text', None],
},
'contract_name' :
{
'header':[1,40, 'text', _render("_('Contract Name')")],
'lines':[1,0, 'text', _render("line.abc_contract_name or ''")],
'totals':[1, 0, 'text', None],
},
'exclusive':
{
'header':[1,10, 'text', _render("_('Exlusive')")],
'lines':[1,0, 'text', _render("line.abc_country.name or ''")],
'totals':[1, 0, 'text', None],
},
}
for t in tbl_products:
abc_tmpl[t['name']]={
'header':[1,3, 'text', _render("_('" + t['name']+"')")],
'lines':[1,0, 'text', _render("line.abc_contract_id.name or ''")],
'totals':[1, 0, 'text', None],
}
return abc_tmpl
_name='abc.contract.search.wizard'
_columns={
'country':fields.many2one('abc.countries','Country'),
'product':fields.many2one('abc.product.list','Product'),
'start_date':fields.date('Start Date'),
'end_date':fields.date('End Date'),
'partner':fields.many2one('res.partner','Partner'),
'product_type':fields.many2one('abc.product.type','Product Type'),
'regions':fields.many2one('abc.regions', 'Regions'),
'exclusive':fields.boolean('Exclusive'),
'contract_type':fields.many2one('abc.contract.types','Contract Type'),
}
def find_product(self, tbl_contractproducts, product_id):
is_there=False
for t in tbl_contractproducts:
if product_id==t['product_id']:
is_there=True
return is_there
def get_contract_products(self, cr, uid, ids, context, contract_id, tbl_products):
products={}
SQLstring = "SELECT abc_contract_product_list.product_id, abc_contract_product_list.contract_id FROM abc_contract_product_list " \
+ "WHERE (((abc_contract_product_list.contract_id) =" + str(contract_id) + "));"
cr.execute(SQLstring)
tbl_contractproducts = cr.dictfetchall()
for t in tbl_products:
if self.find_product(tbl_contractproducts,t['product_id']):
products[t['product_name']]='X'
else:
products[t['product_name']]=''
return products
def export_contract_product(self, cr, uid, ids, context=None):
rst = self.browse(cr, uid, ids)[0]
country_id = rst.country.id
product_id = rst.product.id
start_date = rst.start_date
end_date = rst.end_date
product_type_id = rst.product_type.id
partner_id = rst.partner.id
region_id = rst.regions.id
exclusive = rst.exclusive
contract_type_id = rst.contract_type.id
SQLwhere = ""
SQLstring = "SELECT DISTINCT abc_official_documents.id, abc_official_documents.contract_id, abc_official_documents.name AS doc_name, abc_official_documents.contract_exclusive_agreemnet " \
+ "FROM res_partner INNER JOIN (((abc_contract_countries INNER JOIN (((abc_contract_product_list INNER JOIN (abc_product_type INNER JOIN abc_product_list " \
+ "ON abc_product_type.id = abc_product_list.product_type) ON abc_contract_product_list.product_id = abc_product_list.id) INNER JOIN abc_official_documents ON "\
+ "abc_contract_product_list.contract_id = abc_official_documents.id) INNER JOIN abc_contract_types ON abc_official_documents.contract_type = abc_contract_types.id) "\
+ "ON abc_contract_countries.contract_id = abc_official_documents.id) INNER JOIN abc_countries ON abc_contract_countries.country_id = abc_countries.id) INNER JOIN "\
+ "abc_regions ON abc_countries.country_region = abc_regions.id) ON res_partner.id = abc_official_documents.contract_partner_id "
if country_id:
SQLwhere = " AND ((abc_contract_countries.country_id) = " + str(country_id) + ")"
if product_id:
SQLwhere = SQLwhere + " AND ((abc_contract_product_list.product_id) = " + str(product_id) + ")"
if start_date:
SQLwhere = SQLwhere + " AND ((abc_official_documents.contract_start_date) < " + str(start_date) + ")"
if end_date:
SQLwhere = SQLwhere + " AND ((abc_official_documents.contract_termination_date) < " + str(end_date) + ")"
if partner_id:
SQLwhere = SQLwhere + " AND ((abc_official_documents.contract_partner_id) = " + str(partner_id) +")"
if region_id:
SQLwhere = SQLwhere + " AND ((abc_countries.country_region) = " + str(region_id) + ")"
if exclusive:
SQLwhere = SQLwhere + " AND ((abc_official_documents.contract_exclusive_agreemnet) = true )"
if contract_type_id:
SQLwhere = SQLwhere + " AND ((abc_official_documents.contract_type) = " + str(contract_type_id) + ")"
if product_type_id:
SQLwhere = SQLwhere + " AND ((abc_product_list.product_type) = " +str(product_type_id) + ")"
SQLwhere = SQLwhere[-(len(SQLwhere)-5):] #Vat die eerste "AND" weg (5 karakters)
if ((not SQLwhere) | (len(SQLwhere)==0)):
SQLstring = SQLstring + " LIMIT 100;"
else:
SQLstring = SQLstring + "WHERE (" + SQLwhere + ") LIMIT 100;"
cr.execute(SQLstring)
tblContracts = cr.dictfetchall()
SQLstring = "SELECT abc_product_list.id AS product_id, abc_product_list.name as product_name FROM abc_product_list;"
cr.execute(SQLstring)
tbl_products = cr.dictfetchall()
pivot_table = []
datas={'ids':context.get('active_ids', [])}
for t in tblContracts:
if t:
if t['contract_exclusive_agreemnet']:
excl="Yes"
else:
excl = "No"
contract_table = {
'contract_id': t['contract_id'],
'contract_name': t['doc_name'],
'exclusive':excl,
}
product_table=self.get_contract_products(cr, uid, ids, context, t['id'], tbl_products)
full_table = dict(contract_table.items() + product_table.items())
pivot_table.append(full_table)
datas['contract_list']= pivot_table
return {
'type':'ir.actions.report.xml',
'report_name': 'contract_products',
'datas':datas,
}
abc_contract_search_wizard()
Here is the code for the parser:
class contract_products_parser(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(contract_products_parser, self).__init__(cr, uid, name, context=context)
forc_obj = self.pool.get('abc.contract.search.wizard')
self.context = context
wanted_list = forc_obj._prd_report_xls_fields(cr, uid, context)
template_changes = forc_obj._prd_report_xls_template(cr, uid, context)
self.localcontext.update({
'datetime': datetime,
'wanted_list': wanted_list,
'template_changes': template_changes,
'_': self._,
})
def _(self, src):
lang = self.context.get('lang', 'en_US')
return translate(self.cr, _ir_translation_name, 'report', lang, src) or src
class contract_products_xls(report_xls):
def __init__(self, name, table, rml=False, parser=False, header=True, store=False):
super(contract_products_xls, self).__init__(name, table, rml, parser, header, store)
# Cell Styles
_xs = self.xls_styles
# header
rh_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
self.rh_cell_style = xlwt.easyxf(rh_cell_format)
self.rh_cell_style_center = xlwt.easyxf(rh_cell_format + _xs['center'])
self.rh_cell_style_right = xlwt.easyxf(rh_cell_format + _xs['right'])
# lines
aml_cell_format = _xs['borders_all']
self.aml_cell_style = xlwt.easyxf(aml_cell_format)
self.aml_cell_style_center = xlwt.easyxf(aml_cell_format + _xs['center'])
self.aml_cell_style_date = xlwt.easyxf(aml_cell_format + _xs['left'], num_format_str = report_xls.date_format)
self.aml_cell_style_decimal = xlwt.easyxf(aml_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
# totals
rt_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
self.rt_cell_style = xlwt.easyxf(rt_cell_format)
self.rt_cell_style_right = xlwt.easyxf(rt_cell_format + _xs['right'])
self.rt_cell_style_decimal = xlwt.easyxf(rt_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
self.col_specs_template = {
}
def get_c_specs(self, wanted, col_specs, rowtype, data):
"""
returns 'evaluated' col_specs
Input:
- wanted: element from the wanted_list
- col_specs : cf. specs[1:] documented in xls_row_template method
- rowtype : 'header' or 'data'
- render_space : type dict, (caller_space + localcontext)
if not specified
"""
row = col_specs[wanted][rowtype][:]
row[3]=data[wanted]
row.insert(0, wanted)
return row
return True
def new_xls_write_row(self, ws, row_pos, row_data, header, headrot_style, dark_style,
row_style=default_style, set_column_size=False ):
r = ws.row(row_pos)
orig_style=row_style
for col, size, spec in row_data:
data = spec[4]
if header:
if (col!=0) & (col!=1) & (col!=2):
row_style=headrot_style #+ 'align: rotation 90;'
else:
if data=="X":
row_style=dark_style #+ 'pattern: pattern solid, fore_color 0;'
else:
row_style=orig_style
formula = spec[5].get('formula') and \
xlwt.Formula(spec[5]['formula']) or None
style = spec[6] and spec[6] or row_style
if not data:
# if no data, use default values
data = report_xls.xls_types_default[spec[3]]
if size != 1:
if formula:
ws.write_merge(
row_pos, row_pos, col, col + size - 1, data, style)
else:
ws.write_merge(
row_pos, row_pos, col, col + size - 1, data, style)
else:
if formula:
ws.write(row_pos, col, formula, style)
else:
spec[5]['write_cell_func'](r, col, data, style)
if set_column_size:
ws.col(col).width = spec[2] * 256
return row_pos + 1
def generate_xls_report(self, _p, _xs, data, objects, wb):
wanted_list = _p.wanted_list
self.col_specs_template.update(_p.template_changes)
_ = _p._
#report_name = objects[0]._description or objects[0]._name
report_name = _("Export Contract Countries")
ws = wb.add_sheet(report_name[:31])
ws.panes_frozen = True
ws.remove_splits = True
ws.portrait = 0 # Landscape
ws.fit_width_to_pages = 1
row_pos = 0
_xs = self.xls_styles
headrot_style = _xs['bold'] + _xs['fill'] + _xs['borders_all'] + 'align: rotation 90'
xlwt_headrot=xlwt.easyxf(headrot_style)
dark_style = _xs['borders_all']+'pattern: pattern solid, fore_color 0;'
#self.rh_cell_style = xlwt.easyxf(rh_cell_format)
#self.rh_cell_style_center = xlwt.easyxf(rh_cell_format + _xs['center'])
# set print header/footer
ws.header_str = self.xls_headers['standard']
ws.footer_str = self.xls_footers['standard']
# Title
cell_style = xlwt.easyxf(_xs['xls_title'])
c_specs = [
('report_name', 1, 0, 'text', report_name),
]
row_data = self.xls_row_template(c_specs, ['report_name'])
row_pos = self.new_xls_write_row(ws, row_pos, row_data, False, xlwt_headrot , xlwt.easyxf(dark_style), row_style=cell_style )
row_pos += 1
# Column headers
c_specs = map(lambda x: self.render(x, self.col_specs_template, 'header', render_space={'_': _p._}), wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.new_xls_write_row(ws, row_pos, row_data, True, xlwt_headrot, xlwt.easyxf(dark_style), row_style=self.rh_cell_style, set_column_size=True)
ws.set_horz_split_pos(row_pos)
# account move lines
for line in data['contract_list']:
c_specs = map(lambda x: self.get_c_specs(x, self.col_specs_template, 'lines', line), wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.new_xls_write_row(ws, row_pos, row_data, False, xlwt_headrot, xlwt.easyxf(dark_style), row_style=self.aml_cell_style)
contract_products_xls('report.contract_products',
'abc.contract.search.wizard',
parser=contract_products_parser)
To Create an Excel file or a spreadsheet
“import xlwt” package functionality to create sheet in your Py file.We can define the title, header, number, date, and normal style using xlwt.easyxf().
For example title style is given below
new_style = xlwt.easyxf(‘font:height 230; align: wrap No;border: top thick;border: bottom thick;’)
Define how the border should appear.define the workbook. Workbook is actually what we view in our spreadsheet.
To define workbook,
wbk = xlwt.Workbook()
sheet = wbk.add_sheet(‘New_sheet’, cell_overwrite_ok=True)
for write in to the sheet
sheet.write(4, 4, ‘Spellbound Soft Solution’,font_size)
To change the width and height of a cell,
sheet.col(1).width = 500*12
sheet.row(5).height = 70*5
for more goto :
http://spellboundss.com/xls-report-in-odoo/
Thanks
Simply add this report_xlsx module from the app store.
your_module_name --> report--> my_report.py
your_module_name --> report--> my_report.xml
my_report.py
try:
from openerp.addons.report_xlsx.report.report_xlsx import ReportXlsx
except ImportError:
class ReportXlsx(object):
def __init__(self, *args, **kwargs):
pass
class PartnerXlsx(ReportXlsx):
def generate_xlsx_report(self, workbook, data, partners):
for obj in partners:
report_name = obj.name
# One sheet by partner
sheet = workbook.add_worksheet(report_name[:31])
bold = workbook.add_format({'bold': True})
sheet.write(0, 0, obj.name, bold)
PartnerXlsx('report.res.partner.xlsx', 'res.partner')
my_report.xml
`<report
id="partner_xlsx"
model="res.partner"
string="Print to XLSX"
report_type="xlsx"
name="res.partner.xlsx"
file="res.partner.xlsx"
attachment_use="False"
/>`