diff --git a/openerp/models.py b/openerp/models.py index 93640f8c3dc..58998067441 100644 --- a/openerp/models.py +++ b/openerp/models.py @@ -4595,11 +4595,24 @@ class BaseModel(object): """ lang = self._context.get('lang') if lang and lang != 'en_US': + # Sub-select to return at most one translation per record. + # Even if it shoud probably not be the case, + # this is possible to have multiple translations for a same record in the same language. + # The parenthesis surrounding the select are important, as this is a sub-select. + # The quotes surrounding `ir_translation` are important as well. + unique_translation_subselect = """ + (SELECT DISTINCT ON (res_id) res_id, value + FROM "ir_translation" + WHERE + name = %s AND + lang = %s AND + value != %s + ORDER BY res_id, id DESC) + """ alias, alias_statement = query.add_join( - (table_alias, 'ir_translation', 'id', 'res_id', field), + (table_alias, unique_translation_subselect, 'id', 'res_id', field), implicit=False, outer=True, - extra='"{rhs}"."name" = %s AND "{rhs}"."lang" = %s AND "{rhs}"."value" != %s', extra_params=["%s,%s" % (self._name, field), lang, ""], ) return 'COALESCE("%s"."%s", "%s"."%s")' % (alias, 'value', table_alias, field) diff --git a/openerp/osv/query.py b/openerp/osv/query.py index 3fbdc476d4e..5fe53cfdf87 100644 --- a/openerp/osv/query.py +++ b/openerp/osv/query.py @@ -132,8 +132,8 @@ class Query(object): self.tables.append(alias_statement) join_tuple = (alias, lhs_col, col, outer and 'LEFT JOIN' or 'JOIN') self.joins.setdefault(lhs, []).append(join_tuple) - if extra: - extra = extra.format(lhs=lhs, rhs=alias) + if extra or extra_params: + extra = (extra or '').format(lhs=lhs, rhs=alias) self.extras[(lhs, join_tuple)] = (extra, extra_params) return alias, alias_statement @@ -152,9 +152,11 @@ class Query(object): (join, alias_mapping[rhs], lhs, lhs_col, rhs, rhs_col)) extra = self.extras.get((lhs, (rhs, lhs_col, rhs_col, join))) if extra: - from_clause.append(' AND ') - from_clause.append(extra[0]) - from_params.extend(extra[1]) + if extra[0]: + from_clause.append(' AND ') + from_clause.append(extra[0]) + if extra[1]: + from_params.extend(extra[1]) from_clause.append(')') add_joins_for_table(rhs)