too many values to unpack (expected 2) - Dictionary to JSON - python

I have a big dictionary with more than 50 items. I am trying to return this dictionary in the form of JSON.
The code for that is:-
return HttpResponse(json.dumps(responseData, indent = 0, default=str), content_type="application/json")
There are some date fields in the dictionary and so I mentioned default=str to convert them to string.
When I print the json.dumps, I do see proper values present in the json. But when I put it in HttpResponse, I get the below error:-
too many values to unpack (expected 2)
Could somebody tell me why exactly its happening and what is the workaround?
EDIT:- TRACEBACK
Internal Server Error: /ScApp2/home/App20/Details/
Traceback (most recent call last):
File "\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "\PythonWorkspace\ScApp\ScApp2\views.py", line 88, in ModelDetails
cmsPointScore = PspstCmspointscore.objects.filter(model_id)
File "\Python\Python37\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "\Python\Python37\lib\site-packages\django\db\models\query.py", line 836, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "\Python\Python37\lib\site-packages\django\db\models\query.py", line 854, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1253, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1277, in _add_q
split_subq=split_subq,
File "\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1150, in build_filter
arg, value = filter_expr
ValueError: too many values to unpack (expected 2)

The error is in your query (that's why I asked for the traceback):
cmsPointScore = PspstCmspointscore.objects.filter(model_id)
You should add the field name to the filter expression, for example:
cmsPointScore = PspstCmspointscore.objects.filter(model_id=model_id)

Related

How pass parameter in this method?

Hello I'm newbie Python user.
I study now django queryset. but
query.pyi in _BaseQuerySet's method
def values(self, *fields: Union[str, Combinable], **expressions: Any) -> ValuesQuerySet[_T, Dict[str, Any]]: ...
I want to pass a parameter to that function, but the first code runs, but the second code does not.
here is error code
valuelist = ("col1", "col2")
comment = Comment.objects.annotate(col1=F("contents"), col2=F("comment_depth")).values(valuelist)
and showed up if above code run
Traceback (most recent call last):
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\viewsets.py", line 114, in view
return self.dispatch(request, *args, **kwargs)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "D:\djangostudy\DjangoStudy\member\views.py", line 79, in memberlistrlist nt_depth")).values(valuelist)
comment = Comment.objects.annotate(col1=F("contents"), col2=F("commes\query.py", line 841, in valuesment_depth")).values(valuelist)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\db\models\query.py", line 836, in _valuesels\query.py", line 841, in values
clone = self._values(*fields, **expressions)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\db\models\query.py", line 836, in _values
clone.query.set_values(fields)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\db\models\sql\query.py", line 2172, in set_values
self.add_fields(field_names, True)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\db\models\sql\query.py", line 1863, in add_fields
join_info = self.setup_joins(name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m)
ttributeError: 'tuple' object has no attribute 'split'
14/Mar/2021 19:14:09] "GET /member/memberlist/ HTTP/1.1" 500 116044
not error code
comment = Comment.objects.annotate(col1=F("contents"), col2=F("comment_depth")).values("col1", "col2")
What should I do to get it running normally?
The error is in the .values(…) clause: you can not pass a tuple as parameter. You use iterable unpack to unpack the values of an iterable as individual parameters. This is done by putting an asterisk (*) in front:
Comment.objects.annotate(
col1=F('contents'),
col2=F('comment_depth')
).values(*valuelist)
That being said, often it is not a good idea to work with .values(…) [Django-doc] since it "erodes" the model layer.

Date filters fail in django

I have a function:
def update_coins_table():
# Check if the currency has been updated in the last hour
up_to_date_currency = Currency.objects.filter(
currency_value_in_dollars_date=
[datetime.now(), timedelta(hours=1)]).order_by('-currency_value_in_dollars_date')[:len(coins_ids)]
if up_to_date_currency.exists():
# Return if it is
return
if not do_greeting():
print("Gecko crypto board not reachable. Db setup")
return
crypto_coins_prices = cg.get_price(ids=coins_ids_str, vs_currencies='usd')
datetime_now = datetime.now()
for coin_key in crypto_coins_prices:
coin = Currency(
currency_name=coin_key,
currency_value_in_dollars=crypto_coins_prices[coin_key]['usd'],
currency_value_in_dollars_date=datetime_now)
coin.save()
and get the following error on executing filter(),
up_to_date_currency = Currency.objects.filter(
currency_value_in_dollars_date=
[datetime.now(), timedelta(hours=1)]).order_by('-currency_value_in_dollars_date')[:len(coins_ids)]
Error message:
Internal Server Error: /get_currency/
Traceback (most recent call last):
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\projects\crypto-currency-board\crypto\manage_crypto_currency\views.py", line 21, in get_latest_currency
update_coins_table()
File "C:\projects\crypto-currency-board\crypto\manage_crypto_currency\get_coins_scheduler.py", line 38, in update_coins_table
up_to_date_currency = Currency.objects.filter(
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1319, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\lookups.py", line 76, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1357, in get_prep_value
value = super().get_prep_value(value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1217, in get_prep_value
return self.to_python(value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1318, in to_python
parsed = parse_datetime(value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\utils\dateparse.py", line 107, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
[22/Nov/2020 20:27:44] "GET /get_currency/ HTTP/1.1" 500 142548
The model of 'Currency' is:
class Currency(models.Model):
currency_name = models.CharField(max_length=100)
currency_value_in_dollars = models.FloatField()
currency_value_in_dollars_date = models.DateTimeField()
def __str__(self):
return self.currency_name
Why can't I filter by 'currency_value_in_dollars_date'? check if the currency value has been updated within the last hour.
You can not simply uses a list of two values to filter. If you for example want to retrieve all elements in between you can work with a __range lookup [Django-doc]:
from django.utils.timezone import now
current_time = now()
up_to_date_currency = Currency.objects.filter(
currency_value_in_dollars_date__range=(
current_time-timedelta(hours=1),
current_time
)
).order_by('-currency_value_in_dollars_date')[:len(coins_ids)]
This will thus retrieve all Currency objects between an hour ago and now.
If by
check if the currency value has been updated within the last hour
you mean you want to filter all rows up to 1 hour ago, then replace
currency_value_in_dollars_date=
[datetime.now(), timedelta(hours=1)]
with (notice __gte)
currency_value_in_dollars_date__gte=datetime.now() - timedelta(hours=1)
If you want to filter by array, then you'd have to either use JSONField to match value, or use __in to execute SQL in. Otherwise, you can't filter by array, so what you did is basically invalid.
Depending on your settings, you should probably use timezone.now() from django instead of datetime.

djongo.sql2mongo.SQLDecodeError: FAILED SQL: Error in django while filtering Data

I am trying to filter my product list with price less than filter but getting error. I guess the error is I am unable to pass parameters correctly.
any help would be appreciated.
if you require anymore details, please ask.
Note: it does not works even if I pass the query on filter body static.
thanks in advance.
my method:
def getfilter(request, format=None):
kwargs = {
'{0}__{1}'.format('price', 'lt'): Decimal('1000.00'),
# '{0}__{1}'.format('name', 'endswith'): 'Z'
}
products = Product.objects.all().filter(**kwargs)
serializer = ProductSerializer1(products, many=True)
return Response(serializer.data)
Error I Receive:
Traceback (most recent call last):
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 806, in parse
return handler(self, statement)
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 934, in _select
self._query = SelectQuery(self.db, self.connection_properties, sm, self._params)
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 113, in __init__
super().__init__(*args)
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 74, in __init__
self.parse()
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 153, in parse
raise SQLDecodeError
djongo.sql2mongo.SQLDecodeError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/sunil/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/sunil/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/sunil/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/sunil/.local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/sunil/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/decorators.py", line 55, in handler
return func(*args, **kwargs)
File "/home/sunil/Projects/python/loginBazaar/products/prodView.py", line 219, in getfilter
return Response(serializer.data)
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/serializers.py", line 768, in data
ret = super(ListSerializer, self).data
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/serializers.py", line 686, in to_representation
self.child.to_representation(item) for item in iterable
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/models/query.py", line 274, in __iter__
self._fetch_all()
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/models/query.py", line 1242, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/models/query.py", line 55, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql
cursor.execute(sql, params)
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/cursor.py", line 53, in execute
params)
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 743, in __init__
self.parse()
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 826, in parse
raise exe from e
djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT "products_product"."id", "products_product"."name", "products_product"."vendorId", "products_product"."quantity", "products_product"."shopCode", "products_product"."discountPercent", "products_product"."discountPrice", "products_product"."price", "products_product"."dummyPrice", "products_product"."margin", "products_product"."description", "products_product"."is_verified", "products_product"."category", "products_product"."subCategory", "products_product"."images", "products_product"."sizeChart", "products_product"."attributes", "products_product"."buyCount", "products_product"."thumbnail", "products_product"."productCode", "products_product"."atts" FROM "products_product" WHERE "products_product"."price" < %(0)s ORDER BY "products_product"."productCode" ASC
Version: 1.2.32
It seems like the conversion from Decimal to string failed:
'{0}__{1}'.format('price', 'lt'): Decimal('1000.00'),
and corresponding SQL:
< %(0)s
I guess one of this possible troubles:
your model field price type is incorrect for this conversion
your decimal value have two zero numbers after decimal point - try to
remove the last one

How to fix: 'TypeError: expected string or bytes-like object' when doing unit test on a views.py function

I'm writing a test for a function that returns a JSONResponse. The function works fine on the website but the test always raises a TypeError. It looks like the program fails to get an entry from the database and returns an error instead.
views.py:
def check_availability(request, id):
if request.method == "GET":
response_data = {}
event_date = request.GET.get('event_date', False)
check = None
try:
try:
speaker = Pembicara.objects.get(id = id)
filtered = Booking.objects.filter(speaker = speaker)
check = filtered.get(event_date = event_date)
except ObjectDoesNotExist as e:
pass
except Exception as e:
raise e
if not check:
response_data['available'] = 'ok'
else:
response_data['available'] = 'no'
except Exception as e:
raise e
return JsonResponse(response_data)
tests.py:
def test_date_availability_is_checked(self):
p = self.createPembicara()
c = Client()
date = datetime.date.today()
# request = c.get('/profile/1/check_availability/', event_date=date)
b = self.createBooking()
request = c.get('/profile/1/check_availability/', event_date='1999-12-20')
self.assertEqual(request.status_code, 200)
self.assertJSONEqual(request.content, {'available': 'ok'})
terminal:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
./Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/whitenoise/base.py:116: UserWarning: No directory at: /Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/BookaSpeakers/static/
warnings.warn(u"No directory at: {}".format(root))
E.......
======================================================================
ERROR: test_date_availability_is_checked (speaker_profile.tests.ProfileTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/tests.py", line 69, in test_date_availability_is_checked
request = c.get('/profile/1/check_availability/', event_date='2000-12-20')
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 535, in get
response = super().get(path, data=data, secure=secure, **extra)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 347, in get
**extra,
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 503, in request
raise exc_value
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/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/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/views.py", line 53, in check_availability
raise e
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/views.py", line 47, in check_availability
raise e
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/views.py", line 43, in check_availability
check = filtered.get(event_date = event_date)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get
clone = self.filter(*args, **kwargs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/query.py", line 892, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1290, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1318, in _add_q
split_subq=split_subq, simple_col=simple_col,
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1251, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/lookups.py", line 70, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1270, in get_prep_value
return self.to_python(value)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1232, in to_python
parsed = parse_date(value)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/utils/dateparse.py", line 74, in parse_date
match = date_re.match(value)
TypeError: expected string or bytes-like object
----------------------------------------------------------------------
Ran 9 tests in 0.211s
FAILED (errors=1)
Destroying test database for alias 'default'...
Any help would be appreciated, thank you!
The error likely happens because event_date ends up with the value False, which happens because there was no value for 'event_date' in request.GET.
According to the docs of Client.get(), you have to pass a dict with the GET/POST parameters of the request, not using kwargs.
Try by changing this line (which is using kwargs):
request = c.get('/profile/1/check_availability/', event_date='1999-12-20')
to this (now using a dict as the second parameter)
request = c.get('/profile/1/check_availability/', {'event_date': '1999-12-20'})

getting error while using queryset Q in django view

I am creating the dynamic queryset using Q
while i am printing
build_query[:-1]
i am getting output
Q(owner_id=1)|Q(assigned_to=1)
but when using this in to
consultants = Consultant.objects.filter(*build_query[:-1])
getting an error too many values to unpack
i tried it with ** and without * still its not working.
when i check the type of
print type(build_query[:-1])
i am getting string type. Is the a main cause?
Traceback
Internal Server Error: /api/consultants/my_consultants/
Traceback (most recent call last):
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
return view_func(*args, **kwargs)
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/rest_framework/viewsets.py", line 85, in view
return self.dispatch(request, *args, **kwargs)
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/rest_framework/views.py", line 451, in dispatch
response = self.handle_exception(exc)
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/rest_framework/views.py", line 448, in dispatch
response = handler(request, *args, **kwargs)
File "/home/jagmeet/consultadd_workspace/devenv/ckiller/consultants/api.py", line 170, in my_consultants
consultants = Consultant.objects.filter(*build_query[:-1])
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/django/db/models/manager.py", line 92, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
Q(owner_id=1)|Q(assigned_to=1)
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/django/db/models/query.py", line 691, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/django/db/models/query.py", line 709, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/jagmeet/consultadd_workspace/devenv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1331, in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
consultants = Consultant.objects.filter(*build_query[:-1])
Did u try:
Consultant.objects.filter(*[build_query[:-1],])
args should be a list

Categories