How to execute Django Query as string - django

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!!!

Related

combining __startswith and __in not working

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

Django get_or_create ValueError

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

Unsupported lookup 'level' for DateTimeField or join on the field not permitted

this is my view.py
#list_route(methods=["post"])
def created_in_range(self, request):
response = {}
data = request.POST
start = dateutil.parser.parse(data['start'])
end = dateutil.parser.parse(data['end'])
page_no = data['page_no']
tweets = Tweet.get_created_in_range(start, end, int(page_no))
serializer = TweetSerializer(tweets, many= True)
response["data"] = serializer.data
return Response(response, status= status.HTTP_200_OK)
this is my class method of models.py
#classmethod
def get_created_in_range(cls, start, end, page_no):
"""
Returns all the tweets between start and end.
"""
tweets = cls.objects.filter(created_at__level__gte = start, created_at__level__lt=end )
paginator = Paginator(tweets, 5)
return paginator.page(page_no)
this is the error i get
Internal Server Error: /api/twitter/created_in_range/
Traceback (most recent call last):
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/rest_framework/viewsets.py", line 95, in view
return self.dispatch(request, *args, **kwargs)
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/rest_framework/views.py", line 494, in dispatch
response = self.handle_exception(exc)
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/rest_framework/views.py", line 454, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/rest_framework/views.py", line 491, in dispatch
response = handler(request, *args, **kwargs)
File "/home/kethan/Desktop/twitter_env/twitter_app/api/views.py", line 67, in created_in_range
tweets = Tweet.get_created_in_range(start, end, int(page_no))
File "/home/kethan/Desktop/twitter_env/twitter_app/api/models.py", line 143, in get_created_in_range
tweets = cls.objects.filter(created_at__level__gte = start, created_at__level__lt=end )
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/db/models/query.py", line 836, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/db/models/query.py", line 854, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1253, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1277, in _add_q
split_subq=split_subq,
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1215, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1069, in build_lookup
lhs = self.try_transform(lhs, name)
File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1115, in try_transform
(name, lhs.output_field.__class__.__name__))
django.core.exceptions.FieldError: Unsupported lookup 'level' for DateTimeField or join on the field not permitted.
[25/Feb/2018 02:19:25] "POST /api/twitter/created_in_range/ HTTP/1.1" 500 19151
this above is the response in the server
i dont know why there's such a big deal with date time fields
can someone help me resolving the issue, i am fighting for this for a while now
i dont understand where i am going wrong
please help solving this....
For the tweets in 2 date range, you just need the code below and level is not required.
tweets = cls.objects.filter(created_at__gte = start, created_at__lte=end )
Tweets created date should be greater than start date and lesser than the end date.
I faced this issue, when I mistakenly wrote three underscores instead of two like
___gte instead of __gte

What is '_get_val_from_obj' mechanic does?

I am new to tooling job. Currently my favorite package in Django is outdated and seems no one care by now. Therefore I would like to study it.
Problem:
https://github.com/philippbosch/django-geoposition/issues/100
Traceback (most recent call last):
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/sarit/.pyenv/versions/3.6.4/lib/python3.6/contextlib.py", line 52, in inner
return func(*args, **kwds)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch
response = self.handle_exception(exc)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/mixins.py", line 22, in create
headers = self.get_success_headers(serializer.data)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 537, in data
ret = super(Serializer, self).data
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 504, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/fields.py", line 1858, in to_representation
return self.model_field.value_to_string(obj)
File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/src/django-geoposition/geoposition/fields.py", line 50, in value_to_string
value = self._get_val_from_obj(obj)
AttributeError: 'GeopositionField' object has no attribute '_get_val_from_obj'
Official Docs:
https://docs.djangoproject.com/en/2.0/releases/2.0/
Field._get_val_from_obj() is removed.
Question:
How to solve this error?
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return smart_text(value)
Update:
https://github.com/pennersr/django-allauth/issues/1865
#linaskilius says
Django recommends using the Field.value_from_object() instead.
My Fork:
https://github.com/elcolie/django-geoposition

IndexError: list index out of range in Test case

I have strange problems
I have next code Using TesCase and APIClient to get request with token
class Profile(TestCase):
fixtures = ['profiles.json']
def setUp(self):
self.client = APIClient()
self.user = Profile.objects.get(username='some-username')
self.token = Token.objects.create(user=self.user)
self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)
def test_profile(self):
response = self.client.get('/api/some-username/profile/')
print(response.status_code)
print(response.data)`
Authorization goes well,but the I received error. If i use requests.get with headers (token) to development django server all pass well i receive a correct json response
Full Traceback when i run this test:
Traceback (most recent call last):
File "/home/work/project/profiles/tests.py", line 103, in test_user_profile
response = self.client.get('/api/some-username/profile/')
File "/usr/local/lib/python3.5/dist-packages/rest_framework/test.py", line 291, in get
response = super(APIClient, self).get(path, data=data, **extra)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/test.py", line 208, in get
return self.generic('GET', path, **r)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/test.py", line 237, in generic
method, path, data, content_type, secure, **extra)
File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 416, in generic
return self.request(**r)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/test.py", line 288, in request
return super(APIClient, self).request(**kwargs)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/test.py", line 240, in request
request = super(APIRequestFactory, self).request(**kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 501, in request
six.reraise(*exc_info)
File "/usr/local/lib/python3.5/dist-packages/django/utils/six.py", line 686, in reraise
raise value
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/views.py", line 489, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.5/dist-packages/rest_framework_tracking/mixins.py", line 69, in handle_exception
response = super(BaseLoggingMixin, self).handle_exception(exc)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/views.py", line 449, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/views.py", line 486, in dispatch
response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/generics.py", line 254, in get
return self.retrieve(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/mixins.py", line 58, in retrieve
return Response(serializer.data)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/serializers.py", line 533, in data
ret = super(Serializer, self).data
File "/usr/local/lib/python3.5/dist-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/serializers.py", line 500, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/home/work/project/profiles/serializers.py", line 10, in to_representation
return institute.all()[0].slug
File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 289, in __getitem__
return list(qs)[0]
IndexError: list index out of range
How know what is the problem?