Set certain filter field - python

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.

Related

django-import-export | issue in importing data to database | ValueError: Field 'id' expected a number but got ''

I am using Django-import-export for importing data but facing an error given below.
i am using django 4.0.6 python 3.10.5 with PostgreSql and most latest version of django import export
Code settings i tried to import data to postgresql database by django-import-export
class MemberResource(resources.ModelResource):
Brand=Field()
class Meta:
model = model
fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat')
export_order=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat')
def dehydrate_Brand(self, obj):
return str(obj.Brand.title)
class modelAdmin(ImportExportModelAdmin):
resource_class = MemberResource
list_display=['id','title','Model_code','Chipset','chipset_description','Brand','categories']
search_fields = ['title','Model_code','Chipset',]
fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat')
admin.site.register(model,modelAdmin)
and got below error also attached the image where i exported the data from app and then edited the same and tried to import and stuck with below error.
[Line number: 1 - Field 'id' expected a number but got ''.
2, f9, sd, gf, kjkj, images/sample_3pahsfV.jfif, 1, 1
Traceback (most recent call last):
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 187, in _get_
rel_obj = self.field.get_cached_value(instance)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value
return instance._state.fields_cache\[cache_name\]
KeyError: 'Brand'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\_init_.py", line 1988, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: ''
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 707, in import_row
diff = self.get_diff_class()(self, original, new)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 241, in _init_
self.left = self._export_resource_fields(resource, instance)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 262, in _export_resource_fields
return \[resource.export_field(f, instance) if instance else "" for f in resource.get_user_visible_fields()\]
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 262, in <listcomp>
return \[resource.export_field(f, instance) if instance else "" for f in resource.get_user_visible_fields()\]
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 919, in export_field
return method(obj)
File "C:\Users\gsminfinity\Desktop\Master\admin\firmApp\admin.py", line 20, in dehydrate_Brand
return str(obj.Brand.title)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 205, in _get_
rel_obj = self.get_object(instance)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 168, in get_object
return qs.get(self.field.get_reverse_related_filter(instance))
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\query.py", line 482, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\query.py", line 1071, in filter
return self._filter_or_exclude(False, args, kwargs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\query.py", line 1089, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\query.py", line 1096, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1502, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1532, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1358, in build_filter
return self._add_q(
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1532, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1448, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\sql\query.py", line 1273, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\lookups.py", line 27, in _init_
self.rhs = self.get_prep_lookup()
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\lookups.py", line 85, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\_init_.py", line 1990, in get_prep_value
raise e._class_(
ValueError: Field 'id' expected a number but got ''.][1]
the issue was dehydrating foreign key gives only read-only data which was for the purpose of export only to import we need to use the widgets which will resolve the foreign keys and import the data to database.
Link to Documentation
class MemberResource(resources.ModelResource):
Brand = fields.Field(
column_name='Brand',
attribute='Brand',
widget=ForeignKeyWidget(brand, 'title'))
class Meta:
model = model
fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat')
That means that there are missing values in the "id" column.
I don't know "Django import / export", sounds very good. An old way of mine with any import/export is to export some sample data and then open it in excel or pandas. Because of the following:
You have all the required columns.
The columns are in the correct order.
And if you have test data you can see the data-types of each column.
Take care using Excel because it changes True into TRUE and generates weird date formats.
Another issue is that after importing django u must also be aware of the last "id" number in order to give the correct AutoIncrement for a new record. That's usually corrected with SQL, but maybe "Django-import-export" corrects this automatically.

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

Django case when else in filter

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'))

Django-PolymorphicModels - Error when deleting an instance

It's the first time I'm trying 'PolymorphicModel', maybe there is something I'm doing wrong or I'm trying to do something that is not supported. Is there anyway to get around this?
My simplified model:
from django.polymorphic import PolymorphicModel
class Question(PolymorphicModel):
description = models.TextField(default='')
compound_question = models.ForeignKey('CompoundQuestion',
on_delete=models.CASCADE,
blank=True,
null=True,
related_name='sub_questions')
bonus_question = models.OneToOneField('BonusQuestion',
on_delete=models.CASCADE,
blank=True,
null=True,
related_name='question')
class SimpleQuestion(Question):
pass
class CompoundQuestion(Question):
pass
class BonusQuestion(Question):
pass
If I create the necessary instances,
compound_q = CompoundQuestion()
compound_q.save()
simple_q2 = SimpleQuestion(compound_question=compound_q)
simple_q2.save()
bonus_q = BonusQuestion(compound_question=compound_q)
bonus_q.save()
simple_q1 = SimpleQuestion(bonus_question=bonus_q)
simple_q1.save()
so that in the end I end up with:
compound_q.sub_questions.all()
>>> <PolymorphicQuerySet [<BonusQuestion: BonusQuestion object (5)>, <SimpleQuestion: SimpleQuestion object (8)>]>
After I do compound_q.delete()
I get:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/base.py", line 936, in delete
collector.collect([self], keep_parents=keep_parents)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 245, in collect
field.remote_field.on_delete(self, field, sub_objs, self.using)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 17, in CASCADE
source_attr=field.name, nullable=field.null)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 226, in collect
sub_objs = self.related_objects(related, batch)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 257, in related_objects
**{"%s__in" % related.field.name: objs}
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File ".../Python/Django/env/lib/python3.6/site-packages/polymorphic/query.py", line 173, in _filter_or_exclude
negate, *(list(q_objects) + additional_args), **kwargs
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1340, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1371, in _add_q
check_filterable=check_filterable,
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1274, in build_filter
self.check_related_objects(join_info.final_field, value, join_info.opts)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1115, in check_related_objects
self.check_query_object_type(v, opts, field)
File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1095, in check_query_object_type
(value, opts.object_name))
ValueError: Cannot query "SimpleQuestion object (8)": Must be "BonusQuestion" instance.
Is there something wrong with my model? Everything else seems to be working as expected.
Thanks for reading :)
This appears to be a known bug in the django-polymorphic package. There is a work around suggested here to add a vanilla Manager to your class and to set this manager as the default
class Question(PolymorphicModel):
non_polymorphic = models.Manager()
class Meta
base_manager_name = 'non_polymorphic'

'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