Trying to add rows from a DataFrame into Django model.
models.py:
class CreditIndex_TEST(models.Model):
loanBook = models.ForeignKey(LoanBooks, on_delete=models.CASCADE)
run_date = models.DateField()
index_date = models.DateField()
index_CD = models.IntegerField()
Index_value = models.FloatField()
class Meta:
constraints = [
models.UniqueConstraint(fields= ['loanBook','run_date','index_date','index_CD'], name='unique_CreditIndexPair')
]
views.py:
for index, row in tempDf.iterrows():
obj, created = CreditIndex_TEST.objects.get_or_create(
loanBook=dbname,
run_date= run_date,
index_date=row['Date'],
index_CD=1,
Index_value=row['CreditIndex_CD1']
)
ERROR::
ValueError: Field 'id' expected a number but got 'Botswana_TU'.
I don't understand why I am being asked to specify id. The record I am trying to add to the model does not exist and therefore Django should create it and assign id, not expect it from me?
EDIT (full traceback):
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/gunthermarais/credit-risk/django/RiskLab/Provisions/views.py", line 48, in macroGUI
Index_value=row['CreditIndex_CD1']
File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 575, in update_or_create
obj = self.select_for_update().get(**kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 404, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1350, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1381, in _add_q
check_filterable=check_filterable,
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1311, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1165, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/lookups.py", line 22, in __init__
self.rhs = self.get_prep_lookup()
File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/related_lookups.py", line 115, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1776, in get_prep_value
) from e
ValueError: Field 'id' expected a number but got 'Botswana_TU'.
Related
I am trying to implement bulk_create my inserting multiple objects in
a relation, not sure whether I am doing it right i have added trace back as well below is skill set model
class Skillset(models.Model):
skill_name = models.CharField(max_length=255)
def __str__(self):
return self.skill_name
my view
skill_name = request.POST.getlist('skill_name')
skill_level = request.POST.getlist('skill_level')
print(f'skill name-> {skill_name} skill level ->{skill_level}')
seeker_skll = []
# testing destructing
for skill_nme, skill_lvl in zip(skill_name, skill_level):
skill_set = Skillset.objects.get(skill_name=skill_nme)
seeker_skll.append(Seekerskillset(
skill_set=skill_set, skill_level=skill_lvl, seeker=user))
seeker_skll = Skillset.objects.bulk_create(seeker_skll)
print(seeker_skll)
return redirect('/users/dashboard')
Model
class Seekerskillset(models.Model):
skill_set = models.ForeignKey(Skillset, on_delete=models.CASCADE)
seeker = models.ForeignKey(SeekerProfile, on_delete=models.CASCADE)
skill_level = models.CharField(max_length=25)
class Meta:
verbose_name = 'Seeker skill set'
error i am getting
AttributeError: 'Seekerskillset' object has no attribute 'skill_name'
Traceback (most recent call last):
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\atif\PycharmProjects\my_proj\mysite_jobportal\seekerbuilder\views.py", line 43, in update_details
seeker_skll = Skillset.objects.bulk_create(seeker_skll)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 515, in bulk_create
objs_without_pk, fields, batch_size, ignore_conflicts=ignore_conflicts,
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1293, in _batched_insert
self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1270, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1415, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1360, in as_sql
for obj in self.query.objs
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1360, in <listcomp>
for obj in self.query.objs
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1359, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1310, in pre_save_val
return field.pre_save(obj, add=True)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\__init__.py", line 822, in pre_save
return getattr(model_instance, self.attname)
Exception Type: AttributeError at /users/app_det/
Exception Value: 'Seekerskillset' object has no attribute 'skill_name'
The problem is caused by using Skillset to bulk create Seekerskillset objects.
So change:
seeker_skll = Skillset.objects.bulk_create(seeker_skll)
to:
seeker_skll = Seekerskillset.objects.bulk_create(seeker_skll)
I have 3 Models:
Actor(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
type = models.Charfield(max_length=20)
Organisation(Actor):
name = models.Charfield(max_length=20)
actor = models.OneToOneField(Actor, on_delete=Models.CASCADE)
parent_organisation = models.ForeignKey(Actor, on_delete=models.CASCADE)
CustomUser(AbstractBaseUser,PermissionsMixin,Actor):
name = models.Charfield(max_length=20)
member_of = models.ManyToManyField(Actor, on_delete=models.CASCADE)
I am basically trying to get all users within an organisation:
User and Organisation share a common named id - Actor and Inherit from this class.
I have tried:
user_list = CustomerUser.objects.filter(parent__parent__id=request.session['organisation']
and
user_list = Organisation.objects.filter(parent__parent_user_organisation=request.session[''organisation']
and
user_list = Actor.objects.filter(parent__parent__user_organisation__in=request.session['organisation'])
although I would like to try and keep all queries on the actor model if possible. Eventually, id like to get all users within a multi-tiered organisation structure although for now, I'm happy to get just users based on Organisation_parent rather than ----- Organisation_parent_Organisation_parent etc...
I have changed my model structure to inherited to try and make queries easier but not having much luck.
The full trace:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-
packages/django/db/models/fields/__init__.py", line 2348, in to_python
return uuid.UUID(**{input_form: value})
File "/usr/local/lib/python3.8/uuid.py", line 171, in __init__
raise ValueError('badly formed hexadecimal UUID string')
During handling of the above exception (badly formed hexadecimal UUID string), another exception occurred: File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/src/app/administration/views.py", line 133, in user_list
user_list = Actor.objects.filter(parent__parent__user_organisation__in=request.session['organisation']) File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1350, in add_q
clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter( File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1311, in build_filter
condition = self.build_lookup(lookups, col, value) File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1165, in build_lookup
lookup = lookup_class(lhs, rhs) File "/usr/local/lib/python3.8/site-packages/django/db/models/lookups.py", line 22, in __init__
self.rhs = self.get_prep_lookup() File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related_lookups.py", line 59, in get_prep_lookup
self.rhs = [target_field.get_prep_value(v) for v in self.rhs] File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related_lookups.py", line 59, in <listcomp>
self.rhs = [target_field.get_prep_value(v) for v in self.rhs] File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 945, in get_prep_value
return self.target_field.get_prep_value(value) File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2332, in get_prep_value
return self.to_python(value) File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2350, in to_python
raise exceptions.ValidationError(
Exception Type: ValidationError at /administration/administration/user/list Exception Value: ['“4” is not a valid UUID.']
I'm using Django 3 and Python 3.8 along with the Django rest framework. I have the following model. Notice the many-to-many relationship with addresses ...
class Coop(models.Model):
objects = CoopManager()
name = models.CharField(max_length=250, null=False)
types = models.ManyToManyField(CoopType, blank=False)
addresses = models.ManyToManyField(Address)
enabled = models.BooleanField(default=True, null=False)
phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone')
email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email')
web_site = models.TextField()
I have created the following serializers. I'm having trouble with updating the model so I exluded the create methods for simplicity ...
class AddressTypeField(serializers.PrimaryKeyRelatedField):
queryset = Address.objects
def to_internal_value(self, data):
if type(data) == dict:
locality = data['locality']
state = None if not re.match(r"[0-9]+", str(locality['state'])) else State.objects.get(pk=locality['state'])
locality['state'] = state
locality, created = Locality.objects.get_or_create(**locality)
data['locality'] = locality
address = Address.objects.create(**data)
# Replace the dict with the ID of the newly obtained object
data = address.pk
return super().to_internal_value(data)
...
class CoopSerializer(serializers.ModelSerializer):
types = CoopTypeSerializer(many=True, allow_empty=False)
addresses = AddressTypeField(many=True)
phone = ContactMethodPhoneSerializer()
email = ContactMethodEmailSerializer()
class Meta:
model = Coop
fields = '__all__'
...
def update(self, instance, validated_data):
"""
Update and return an existing `Coop` instance, given the validated data.
"""
instance.name = validated_data.get('name', instance.name)
try:
coop_types = validated_data['types']
instance.types.clear() # Disassociates all CoopTypes from instance.
for item in coop_types:
coop_type, _ = CoopType.objects.get_or_create(**item)
instance.types.add(coop_type)
except KeyError:
pass
instance.addresses = validated_data.get('addresses', instance.addresses)
instance.enabled = validated_data.get('enabled', instance.enabled)
phone = validated_data.pop('phone', {})
email = validated_data.pop('email', {})
instance.phone = ContactMethod.objects.create(type=ContactMethod.ContactTypes.PHONE, **phone)
instance.email = ContactMethod.objects.create(type=ContactMethod.ContactTypes.EMAIL, **email)
instance.web_site = validated_data.get('web_site', instance.web_site)
instance.web_site = validated_data.get('web_site', instance.web_site)
instance.save()
return instance
What's the right way to handle updating the address fields of my main Coop model? When I submit a payload like below (I have IDs included with my address member field objects) ...
{"id":927,"types":[{"id":76,"name":"ct"}],"addresses":[{"id":824,"street_number":"","route":"","raw":"","formatted":"4750 N Woodlawn Rd","latitude":null,"longitude":null,"locality":{"id":54,"name":"Chicago","postal_code":"60640","state":19313}}],"phone":{"phone":"3039468888"},"email":{"email":"dave#hello.com"},"name":"Dave Coop","enabled":true,"web_site":"http://www.example.org"}
And submit it via PATCH, I get the error below. Is there some way to tell my serializer to only update the member field if an ID is created instead of trying to create it from scratch each time?
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/directory/views.py", line 78, in put
if serializer.is_valid():
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 234, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 433, in run_validation
value = self.to_internal_value(data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 490, in to_internal_value
validated_value = field.run_validation(primitive_value)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 565, in run_validation
value = self.to_internal_value(data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/relations.py", line 519, in to_internal_value
return [
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/relations.py", line 520, in <listcomp>
self.child_relation.to_internal_value(item)
File "/Users/davea/Documents/workspace/chicommons/maps/web/directory/serializers.py", line 35, in to_internal_value
address = Address.objects.create(**data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 433, in create
obj.save(force_insert=True, using=self.db)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 745, in save
self.save_base(using=using, force_insert=force_insert,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 782, in save_base
updated = self._save_table(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 886, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 923, in _do_insert
return manager._insert(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1377, in execute_sql
cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 74, in execute
return self.cursor.execute(query, args)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/cursors.py", line 170, in execute
result = self._query(query)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/cursors.py", line 328, in _query
conn.query(q)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/connections.py", line 517, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/connections.py", line 732, in _read_query_result
result.read()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/connections.py", line 1075, in read
first_packet = self.connection._read_packet()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/connections.py", line 684, in _read_packet
packet.check_error()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
django.db.utils.IntegrityError: (1062, "Duplicate entry '824' for key 'address_address.PRIMARY'")
try using partial=True in serializer
I have a QuerySet and an array of strings that I want to test against the QuerySet.
The problem is the values I want to check are foreignKeys and the important characters of the foreignKey are in the beginning.
The query I thought would work is this:
materials_comparison_list.extend(materials_non_eu.filter(code__code__startswith__in=headings_list))
materials_non_eu is the QuerySet, headings_list is the array
However when running that it returns the following error:
django.core.exceptions.FieldError: Unsupported lookup 'startswith' for CharField or join on the field not permitted, perhaps you meant startswith or istartswith
I tried to change the place or __startswith and __in but that produces the same error (different words)
The models for materials looks like this:
class Materials(models.Model):
id = models.AutoField(primary_key=True)
row = models.IntegerField(null=True)
code = models.ForeignKey('HS_code', on_delete=models.CASCADE, null=True)
...
The model for the code looks like this:
class HS_Code(models.Model):
id = models.AutoField(primary_key=True)
code = models.CharField(max_length=10, unique=False)
....
The complete console output:
Traceback (most recent call last):
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler
return func(*args, **kwargs)
File "/Users/5knnbdwm/Python_env/FlexOrigin/main/user.py", line 1115, in api_user_summary_v2
print(Calculation_Master(
File "/Users/5knnbdwm/Python_env/FlexOrigin/main/cluster_v2.py", line 60, in Calculation_Master
MAXNOM(session, materials, country, rule_block[1])
File "/Users/5knnbdwm/Python_env/FlexOrigin/main/cluster_v2.py", line 140, in MAXNOM
materials_comparison_list.extend(materials_non_eu.filter(
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1350, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1311, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1150, in build_lookup
lhs = self.try_transform(lhs, name)
File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1198, in try_transform
raise FieldError(
django.core.exceptions.FieldError: Unsupported lookup 'startswith' for CharField or join on the field not permitted, perhaps you meant startswith or istartswith?
You can not combine the two, but you can make a disjunctive filter with a Q object:
from django.db.models import Q
materials_comparison_list.extend(
materials_non_eu.filter(Q(
*[('code__code__startswith', heading) for heading in headings_list],
_connector=Q.OR
))
)
I want to make a query in Django ORM like this:
query_string = "optionA=True,optionB=True,optionC=True"
data = ModelObject.objects.filter(query_string)
This code is giving following error:
Traceback (most recent call last):
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/root/hellomeets/hellomeets/frontend/views.py", line 74, in post
filtered_emails = HelloMeetsMailList.objects.filter(final_query)
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/db/models/query.py", line 784, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1250, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1276, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1151, in build_filter
arg, value = filter_expr
ValueError: too many values to unpack
I also tried eval() but it didn't work.
Is there any way so that I don't need to write raw sql query
from django.db.models import Q
query_string=Q(optionA=True) & Q(optionB=True) & Q(optionC=True)
data = ModelObject.objects.filter(query_string)
for more details:
https://docs.djangoproject.com/en/2.1/topics/db/queries/#complex-lookups-with-q-objects
If you really need to use that string (which seems like a very hacky way to query Django models) you can split and convert it into a dict:
s = "optionA=True,optionB=True,optionC=True"
kwargs = {}
for e in s.split(','):
k, v = e.split('=')
kwargs[k] = bool(v)
and then unpack that dict in the filter() method
data = ModelObject.objects.filter(**kwargs)
But this is not really recomended!!!