[python] TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

I having trouble passing a function as a parameter to another function. This is my code:

ga.py:

def display_pageviews(hostname):
    pageviews_results = get_pageviews_query(service, hostname).execute()
    if pageviews_results.get('rows', []):
        pv = pageviews_results.get('rows')
        return pv[0]
    else:
        return None


def get_pageviews_query(service, hostname):  
    return service.data().ga().get(
        ids=VIEW_ID,
        start_date='7daysAgo',
        end_date='today',
        metrics='ga:pageviews',
        sort='-ga:pageviews',
        filters='ga:hostname==%s' % hostname,)

models.py:

class Stats(models.Model):
    user = models.OneToOneField('auth.User')
    views = models.IntegerField()
    visits = models.IntegerField()
    unique_visits = models.IntegerField()

updatestats.py:

class Command(BaseCommand):

    def handle(self, *args, **options):
        users = User.objects.all()
        try:
            for user in users:
                hostname = '%s.%s' % (user.username, settings.NETWORK_DOMAIN)
                stats = Stats.objects.update_or_create(
                    user=user,
                    views=display_pageviews(hostname),
                    visits=display_visits(hostname),
                    unique_visits=display_unique_visits(hostname),)
        except FieldError:
            print ('There was a field error.')

When I run this: python manage.py updatestats I get the error:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

I don't know what's causing this. I've tried converting it to a string, but I get the same error. Any ideas?

Full traceback:

Traceback (most recent call last):
  File "manage.py", line 20, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/core/management/__init__.py", line 345, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "/Users/myusername/project/Dev/project_files/project/main/management/commands/updatestats.py", line 23, in handle
    unique_visits=display_unique_visits(hostname),)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/manager.py", line 122, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/query.py", line 480, in update_or_create
    obj = self.get(**lookup)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/query.py", line 378, in get
    clone = self.filter(*args, **kwargs)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/query.py", line 790, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/query.py", line 808, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/sql/query.py", line 1243, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/sql/query.py", line 1269, in _add_q
    allow_joins=allow_joins, split_subq=split_subq,
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/sql/query.py", line 1203, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/sql/query.py", line 1099, in build_lookup
    return final_lookup(lhs, rhs)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/lookups.py", line 19, in __init__
    self.rhs = self.get_prep_lookup()
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/lookups.py", line 57, in get_prep_lookup
    return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1860, in get_prep_lookup
    return super(IntegerField, self).get_prep_lookup(lookup_type, value)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 744, in get_prep_lookup
    return self.get_prep_value(value)
  File "/Users/myusername/project/Dev/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1854, in get_prep_value
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

Edit:

Alright, I understand what the issue is. I used the shell to get the type of function output:

>>> type(display_pageviews('test.domain.com'))
<class 'list'>

I tried with this but it is still considered as a list:

pv = pageviews_results.get('rows')[0]
    return pv

This question is related to python django python-3.x

The answer is


What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?