Django case when else in filter - python

I need a similar code to this SQL:
SELECT * FROM tab WHERE a = CASE WHEN x IS NULL THEN b ELSE c END
my attempt, but to no success:
model.objects.filter(a=Q(Case(When(x__isnull=True, then='b'), default='c')))
when I try to run, I get this error:
Traceback (most recent call last):
File "<input>", line 2, in <module>
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1340, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1371, in _add_q
check_filterable=check_filterable,
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1249, in build_filter
value = self.resolve_lookup_value(value, can_reuse, allow_joins, simple_col)
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1058, in resolve_lookup_value
value = value.resolve_expression(self, **kwargs)
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query_utils.py", line 95, in resolve_expression
check_filterable=False,
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1371, in _add_q
check_filterable=check_filterable,
File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1237, in build_filter
arg, value = filter_expr
TypeError: cannot unpack non-iterable Case object

You should not wrap this in a Q object, since a Q object is a condition, a Case is not something that can be True or False:
from django.db.models import Case, When
model.objects.filter(a=Case(When(x__isnull=True, then='b'), default='c'))
Note that you can replace x__isnull=True with simply x=None, which is slightly shorter:
from django.db.models import Case, When
model.objects.filter(a=Case(When(x=None, then='b'), default='c'))

Related

Odoo 14 enterprise POS close session error (ProgrammingError: can't adapt type 'res.partner')

when i try to close my session and post entries for my POS,
I had this error :
Odoo Server Error
Traceback (most recent call last):
File "/opt/odoo14/odoo/addons/base/models/ir_http.py", line 237, in _dispatch
result = request.dispatch()
File "/opt/odoo14/odoo/http.py", line 683, in dispatch
result = self._call_function(**self.params)
File "/opt/odoo14/odoo/http.py", line 359, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/opt/odoo14/odoo/service/model.py", line 94, in wrapper
return f(dbname, *args, **kwargs)
File "/opt/odoo14/odoo/http.py", line 347, in checked_call
result = self.endpoint(*a, **kw)
File "/opt/odoo14/odoo/http.py", line 912, in call
return self.method(*args, **kw)
File "/opt/odoo14/odoo/http.py", line 531, in response_wrap
response = f(*args, **kw)
File "/opt/odoo14/addons/web/controllers/main.py", line 1393, in call_button
action = self._call_kw(model, method, args, kwargs)
File "/opt/odoo14/addons/web/controllers/main.py", line 1381, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/opt/odoo14/odoo/api.py", line 396, in call_kw
result = _call_kw_multi(method, model, args, kwargs)
File "/opt/odoo14/odoo/api.py", line 383, in _call_kw_multi
result = method(recs, *args, **kwargs)
File "/opt/odoo14/custom_addons/bi_pos_pay_later/models/pos_session.py", line 35, in action_pos_session_closing_control
session.action_pos_session_close()
File "/opt/odoo14/addons/point_of_sale/models/pos_session.py", line 295, in action_pos_session_close
return self._validate_session()
File "/opt/odoo14/addons/point_of_sale/models/pos_session.py", line 311, in _validate_session
self.with_company(self.company_id)._create_account_move()
File "/opt/odoo14/addons/point_of_sale/models/pos_session.py", line 408, in _create_account_move
data = self._create_invoice_receivable_lines(data)
File "/opt/odoo14/addons/point_of_sale/models/pos_session.py", line 657, in _create_invoice_receivable_lines
receivable_line = MoveLine.create(vals)
File "", line 2, in create
File "/opt/odoo14/odoo/api.py", line 345, in _model_create_multi
return create(self, arg)
File "/opt/odoo14/addons/account/models/account_move.py", line 3843, in create
lines = super(AccountMoveLine, self).create(vals_list)
File "", line 2, in create
File "/opt/odoo14/odoo/api.py", line 345, in _model_create_multi
return create(self, arg)
File "/opt/odoo14/odoo/addons/base/models/ir_fields.py", line 533, in create
recs = super().create(vals_list)
File "", line 2, in create
File "/opt/odoo14/odoo/api.py", line 345, in _model_create_multi
return create(self, arg)
File "/opt/odoo14/odoo/models.py", line 3868, in create
records = self._create(data_list)
File "/opt/odoo14/odoo/models.py", line 3974, in _create
cr.execute(query, params)
File "", line 2, in execute
File "/opt/odoo14/odoo/sql_db.py", line 101, in check
return f(self, *args, **kwargs)
File "/opt/odoo14/odoo/sql_db.py", line 298, in execute
res = self._obj.execute(query, params)
Exception
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/odoo14/odoo/http.py", line 639, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/opt/odoo14/odoo/http.py", line 315, in _handle_exception
raise exception.with_traceback(None) from new_cause
psycopg2.ProgrammingError: can't adapt type 'res.partner'
this happened especially if some of my POS orders are invoiced ( defined with customers ) How can i solve it ?
i use odoo 14 enterprise hosted on premise.
The shared error log says you use third-party modules like 'bi_pos_pay_later'. Kindly make sure that these modules are not the ones causing errors by creating a new database with these modules and checking the same workflow. If you find that the issue is with the third-party modules, kindly report the same to its developers since they will be better suited to help you.

Django postgres full text search error "Unsupported lookup 'search' for CharField"

All similar problems have been solved by adding django.contrib.postgres to INSTALLED_APPS in settings.py, which is also all the docs mention on how to use the lookup. I've already done this and the lookup still isn't working, despite whether I use __search or search= for the filter. Any ideas? Do I need to register the lookup in my model myself?
settings.py:
INSTALLED_APPS = [
...
'django.contrib.postgres',
# my_project
'my_project.apps.appname',
'my_project.apps.appname',
...
error line:
x = y.objects.filter(description__search="example")
traceback:
File "d:\proj\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "d:\proj\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "d:\proj\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "d:\proj\env\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "d:\proj\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "d:\proj\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "d:\proj\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "d:\proj\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "D:\proj\my_project\my_project\apps\appname\views.py", line 306, in get
x = y.objects.filter(description__search="example")
File "d:\proj\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "d:\proj\env\lib\site-packages\django\db\models\query.py", line 941, in filter
return self._filter_or_exclude(False, args, kwargs)
File "d:\proj\env\lib\site-packages\django\db\models\query.py", line 961, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "d:\proj\env\lib\site-packages\django\db\models\query.py", line 968, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "d:\proj\env\lib\site-packages\django\db\models\sql\query.py", line 1393, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "d:\proj\env\lib\site-packages\django\db\models\sql\query.py", line 1412, in _add_q
child_clause, needed_inner = self.build_filter(
File "d:\proj\env\lib\site-packages\django\db\models\sql\query.py", line 1347, in build_filter
condition = self.build_lookup(lookups, col, value)
File "d:\proj\env\lib\site-packages\django\db\models\sql\query.py", line 1187, in build_lookup
lhs = self.try_transform(lhs, lookup_name)
File "d:\proj\env\lib\site-packages\django\db\models\sql\query.py", line 1226, in try_transform
raise FieldError(
django.core.exceptions.FieldError: Unsupported lookup 'search' for CharField or join on the field not permitted.```
x = y.objects.filter(description__search="example")
Search lookup is specific to PostrgreSQL so you need to set up PosgreSQL db first.
https://docs.djangoproject.com/en/4.0/ref/contrib/postgres/search/
If you want to just look for a string in CharField or TextField you can use
x = y.objects.filter(description__icontains="example")
docs: https://docs.djangoproject.com/en/4.0/ref/models/querysets/#icontains

Iam trying to install a new module in odoo but error occuring, AttributeError: 'str' object has no attribute 'setdefault'

I am trying to use the ODOO server, however I am getting this exception. Seems like a configuraton issue:
Traceback (most recent call last):
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/http.py", line 640, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/http.py", line 316, in _handle_exception
raise exception.with_traceback(None) from new_cause
**AttributeError: 'str' object has no attribute 'setdefault'**
Odoo Server Error
Traceback (most recent call last):
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/addons/base/models/ir_http.py", line 237, in _dispatch
result = request.dispatch()
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/http.py", line 684, in dispatch
result = self._call_function(**self.params)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/http.py", line 360, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/service/model.py", line 94, in wrapper
return f(dbname, *args, **kwargs)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/http.py", line 348, in checked_call
result = self.endpoint(*a, **kw)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/http.py", line 913, in __call__
return self.method(*args, **kw)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/http.py", line 532, in response_wrap
response = f(*args, **kw)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/addons/web/controllers/main.py", line 1368, in call_button
action = self._call_kw(model, method, args, kwargs)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/addons/web/controllers/main.py", line 1356, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/api.py", line 396, in call_kw
result = _call_kw_multi(method, model, args, kwargs)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/api.py", line 383, in _call_kw_multi
result = method(recs, *args, **kwargs)
File "<decorator-gen-71>", line 2, in button_immediate_install
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/addons/base/models/ir_module.py", line 73, in check_and_log
return method(self, *args, **kwargs)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/addons/base/models/ir_module.py", line 474, in button_immediate_install
return self._button_immediate_function(type(self).button_install)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/addons/base/models/ir_module.py", line 592, in _button_immediate_function
modules.registry.Registry.new(self._cr.dbname, update_module=True)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/modules/registry.py", line 89, in new
odoo.modules.load_modules(registry._db, force_demo, status, update_module)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/modules/loading.py", line 453, in load_modules
processed_modules += load_marked_modules(cr, graph,
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/modules/loading.py", line 346, in load_marked_modules
loaded, processed = load_module_graph(
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/modules/loading.py", line 197, in load_module_graph
registry.setup_models(cr)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/modules/registry.py", line 269, in setup_models
model._setup_base()
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/models.py", line 2780, in _setup_base
self._add_field(name, field.new())
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/models.py", line 402, in _add_field
field.setup_base(self, name)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/fields.py", line 278, in setup_base
self._setup_attrs(model, name)
File "/home/ajay/PycharmProjects/odoo/odoo-14.0/odoo/fields.py", line 2282, in _setup_attrs
ondelete.setdefault(key, 'set null')
Exception
The above exception was the direct cause of the following exception:

Set certain filter field

I have one innormal idea to get object through function and set to it certain field for filtering
It will look as follows
get_course(name='math')
# or
get_course(id=12)
# and so on
def get_course(**kwargs):
for key, val in kwargs:
return Course.objects.get(key=val)
I've tried:
key = 'id'
val = 1
Course.objects.filter(key=val)
And result was:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\query.py", line 892, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\query.py", line 910, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\sql\query.py", line 1290, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\sql\query.py", line 1318, in _add_q
split_subq=split_subq, simple_col=simple_col,
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\sql\query.py", line 1190, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\sql\query.py", line 1049, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "C:\Users\lyf20\Documents\Student\OpenUniProject\OpenUni\venv\lib\site-packages\django\db\models\sql\query.py", line 1420, in names_to_path
"Choices are: %s" % (name, ", ".join(available)))
django.core.exceptions.FieldError: Cannot resolve keyword 'key' into field. Choices are: complexity, course, created, description, id, image, image_courses_and_course, image_dash, is_active, is_certificated, is_video, modules, name, question, queue_number, quiz, selected_courses, short_description, tagged_items, tags, total_ended, total_started, total_watches, updated, users_ended, users_likes, users_started, video_link
So is it possible to make this stuff?
To pass variable keyword parameters to functions in python you can use dictionary unpacking
This
foo(**{'bar': 'baz'})
Is equivalent to
foo(bar='baz')
You could probably do something like this
def get_course(**kwargs):
return Course.objects.get(**kwargs)
Have you tried running this code and if so, what's the issue you're running into? This looks fine to me.

'NoneType' object is not iterable For selection field in odoo 9

"Error"
File "/home/tushar/odoo1/openerp/fields.py", line 1528, in get_values
return [value for value, _ in selection]
TypeError: 'NoneType' object is not iterable
Stachtrace:
Odoo Server Error
Traceback (most recent call last):
File "/home/tushar/odoo1/openerp/http.py", line 648, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/tushar/odoo1/openerp/http.py", line 685, in dispatch
result = self._call_function(**self.params)
File "/home/tushar/odoo1/openerp/http.py", line 321, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/tushar/odoo1/openerp/service/model.py", line 118, in wrapper
return f(dbname, *args, **kwargs)
File "/home/tushar/odoo1/openerp/http.py", line 314, in checked_call
result = self.endpoint(*a, **kw)
File "/home/tushar/odoo1/openerp/http.py", line 964, in __call__
return self.method(*args, **kw)
File "/home/tushar/odoo1/openerp/http.py", line 514, in response_wrap
response = f(*args, **kw)
File "/home/tushar/odoo1/addons/web/controllers/main.py", line 888, in call_kw
return self._call_kw(model, method, args, kwargs)
File "/home/tushar/odoo1/addons/web/controllers/main.py", line 880, in _call_kw
return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
File "/home/tushar/odoo1/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)
File "/home/tushar/odoo1/openerp/api.py", line 381, in old_api
result = method(recs, *args, **kwargs)
File "/home/tushar/odoo1/openerp/models.py", line 6028, in onchange
record = self.new(values)
File "/home/tushar/odoo1/openerp/api.py", line 248, in wrapper
return new_api(self, *args, **kwargs)
File "/home/tushar/odoo1/openerp/models.py", line 5595, in new
record._cache.update(record._convert_to_cache(values, update=True))
File "/home/tushar/odoo1/openerp/models.py", line 5490, in _convert_to_cache
for name, value in values.iteritems()
File "/home/tushar/odoo1/openerp/models.py", line 5491, in <dictcomp>
if name in fields
File "/home/tushar/odoo1/openerp/fields.py", line 1533, in convert_to_cache
if value in self.get_values(record.env):
File "/home/tushar/odoo1/openerp/fields.py", line 1528, in get_values
return [value for value, _ in selection]
TypeError: 'NoneType' object is not iterable
I got This Error for dynamic selection for selection field in odoo. I provide the code I have done. Please help me out of this
from openerp import models, fields, api
from test.test_support import temp_cwd
class scantech_laser_product_template(models.Model):
_name='product.template'
_inherit='product.template'
values2=[('ECDS0','ECDS0'),('ECDS1','ECDS1'),('ECDS2','ECDS2')]
main_category = fields.Selection([('SL0','SL0'),('SL1','SL1'),('SL2','SL2')],string="Main Category")
#api.multi
#api.depends("main_category")
def _get_selection_name(self):
if self.main_category == "SL0":
return [("ESDS1","ESDS1")]
sub_category = fields.Selection(selection=_get_selection_name,string="Sub Category")
When I am selecting the main category field it showing above error
The problem is that you're not returning a default value when your condition evaluates to false (and functions/methods in python that return nothing return None) so a workaround would be to do something like this
#api.multi
#api.depends("main_category")
def _get_selection_name(self):
if self.main_category == "SL0":
return [("ESDS1","ESDS1")]
return [("default", "Default")] # can be anything you want as the default value
or you can make your selection field have a default value, which makes the condition to always evaluate to true and eliminates the need for a default return value in _get_selection_name
main_category = fields.Selection([('SL0','SL0'),('SL1','SL1'),('SL2','SL2')],string="Main Category", default="SLO")

Categories

Resources