Django 保存到 DB:TypeError:int() 参数必须是字符串、类似字节的对象或数字,而不是“元组”
Posted
技术标签:
【中文标题】Django 保存到 DB:TypeError:int() 参数必须是字符串、类似字节的对象或数字,而不是“元组”【英文标题】:Django save to DB: TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple' 【发布时间】:2017-10-27 16:14:28 【问题描述】:我在将数据保存到数据库时遇到了问题。
@staticmethod
def _save(account, proxy,
proxy_provider_id, period,
country, start_date,
price, meta,
account_type, ip):
try:
period = int(period)
end_date = start_date + timedelta(days=period)
prx = Proxy()
prx.account = account
prx.proxy = proxy
prx.proxy_provider_id = proxy_provider_id
prx.period = period,
prx.country = country,
prx.start_date = start_date
prx.end_date = end_date
prx.price = price
prx.meta = meta
prx.ip = ip
print('\n')
print('Save proxy '.format(prx))
print('account: type '.format(account, type(account)))
print('proxy: type '.format(proxy, type(proxy)))
print('proxy id: type '.format(proxy_provider_id, type(proxy_provider_id)))
print('country: type '.format(country, type(country)))
print('start date: type '.format(start_date, type(start_date)))
print('end date: type '.format(end_date, type(end_date)))
print('price: type '.format(price, type(price)))
print('meta: type '.format(meta, type(meta)))
print('ip: type '.format(ip, type(ip)))
print('\n')
prx.save() # exception raised there
payment = [start_date.strftime('%Y/%m/%d'),
end_date.strftime("%Y/%m/%d")]
payments = json.loads(account.history_of_payments)
payments.append(payment)
account.history_of_payments = json.dumps(payments)
account.account_type = account_type
print('\n')
print('Save account '.format(prx))
print('payment: type '.format(payments, type(payments)))
print('account type: type '.format(account_type, type(account_type)))
print('\n')
account.save(update_fields=['history_of_payments', 'account_type'])
log.debug('Update account '.format(account))
except Exception:
raise ProxyException('Exception, when trying to save proxy for '
'date price meta '
.format(proxy, country, account.username,
start_date, price, meta))
else:
log.info('Save new proxy for from to price meta '
.format(proxy, country, account.username,
start_date, end_date, price, meta))
return True
我不知道是什么原因导致了这个异常,因为我没有尝试保存任何元组。您可以查看日志。只有 srting、float、object、datetime 和 int 类型。
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
完整的日志是:
Save proxy Proxy object
account: InstagramAccount object type <class 'models.models.InstagramAccount'>
proxy: jFdDVV:BxorDV@107.191.105.212:17160 type <class 'str'>
proxy id: 762064 type <class 'int'>
country: us type <class 'str'>
start date: 2017-05-26 16:09:31.604467+00:00 type <class 'datetime.datetime'>
end date: 2017-05-29 16:09:31.604467+00:00 type <class 'datetime.datetime'>
price: 3.6 type <class 'float'>
meta: "2017/05/26": "time": "16:09:13", "proxy_type": "http", "account_type": "trial", "country": "us", "proxy": "jFdDVV:BxorDV@107.191.105.212:17160", "price": 3.6, "currency": "RUB" type <class 'str'>
ip: 109.86.13.23 type <class 'str'>
[2017-05-26 16:09:31,604] DEBUG Proxy jFdDVV:BxorDV@107.191.105.212:17160 check is successful
--- Logging error ---
Traceback (most recent call last):
File "/usr/instafy_py/src/service/views.py", line 130, in create_instagram_account
username=username)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/query.py", line 385, in get
self.model._meta.object_name
models.models.DoesNotExist: InstagramAccount matching query does not exist.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/instafy_py/src/proxy/manager.py", line 208, in _save
prx.save()
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/base.py", line 796, in save
force_update=force_update, update_fields=update_fields)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/base.py", line 824, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/base.py", line 908, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/base.py", line 947, in _do_insert
using=using, raw=raw)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/query.py", line 1045, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1053, in execute_sql
for sql, params in self.as_sql():
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1006, in as_sql
for obj in self.query.objs
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1006, in <listcomp>
for obj in self.query.objs
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1005, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 945, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 755, in get_db_prep_save
prepared=False)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 747, in get_db_prep_value
value = self.get_prep_value(value)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1832, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/instafy_py/src/service/views.py", line 169, in create_instagram_account
3, 'trial')
File "/usr/instafy_py/src/proxy/manager.py", line 156, in buy
account_type, ip)
File "/usr/instafy_py/src/proxy/manager.py", line 229, in _save
start_date, price, meta))
proxy.manager.ProxyException: Exception, when trying to save proxy jFdDVV:BxorDV@107.191.105.212:17160 us for guv.vop date 2017-05-26 16:09:31.604467+00:00 price 3.6 meta "2017/05/26": "time": "16:09:13", "proxy_type": "http", "account_type": "trial", "country": "us", "proxy": "jFdDVV:BxorDV@107.191.105.212:17160", "price": 3.6, "currency": "RUB"
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/python/lib/python3.5/logging/__init__.py", line 980, in emit
msg = self.format(record)
File "/opt/python/lib/python3.5/logging/__init__.py", line 830, in format
return fmt.format(record)
File "/opt/python/lib/python3.5/logging/__init__.py", line 567, in format
record.message = record.getMessage()
File "/opt/python/lib/python3.5/logging/__init__.py", line 330, in getMessage
msg = msg % self.args
TypeError: not all arguments converted during string formatting
Call stack:
File "/opt/python/lib/python3.5/threading.py", line 882, in _bootstrap
self._bootstrap_inner()
File "/opt/python/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/opt/python/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "/opt/python/lib/python3.5/socketserver.py", line 625, in process_request_thread
self.finish_request(request, client_address)
File "/opt/python/lib/python3.5/socketserver.py", line 354, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/opt/python/lib/python3.5/socketserver.py", line 681, in __init__
self.handle()
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/servers/basehttp.py", line 174, in handle
handler.run(self.server.get_app())
File "/opt/python/lib/python3.5/wsgiref/handlers.py", line 137, in run
self.result = application(self.environ, self.start_response)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__
return self.application(environ, start_response)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 170, in __call__
response = self.get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/base.py", line 124, in get_response
response = self._middleware_chain(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/usr/instafy_py/src/middlewares/startup_middleware.py", line 13, in __call__
response = self.get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
response = self.get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
response = self.get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
response = self.get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
response = self.get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
response = self.get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
response = self.get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
response = self.get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
response = self.get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/usr/instafy_py/.virtualenvs/instafy_py/lib/python3.5/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/instafy_py/src/service/views.py", line 171, in create_instagram_account
log.exception('Something wrong with proxy', e)
Message: 'Something wrong with proxy'
Arguments: (ProxyException('Exception, when trying to save proxy jFdDVV:BxorDV@107.191.105.212:17160 us for guv.vop date 2017-05-26 16:09:31.604467+00:00 price 3.6 meta "2017/05/26": "time": "16:09:13", "proxy_type": "http", "account_type": "trial", "country": "us", "proxy": "jFdDVV:BxorDV@107.191.105.212:17160", "price": 3.6, "currency": "RUB" ',),)
所有数据类型都与模型匹配
class InstagramAccount(models.Model):
username = models.CharField(max_length=45, primary_key=True)
password = models.CharField(max_length=45)
account_id_account = models.ForeignKey(Account, models.DO_NOTHING, db_column='account_id_account')
expired_date = models.DateTimeField(null=False)
history_of_payments = models.TextField(blank=True, null=True)
account_type = models.TextField(default='trial')
class Meta:
managed = False
db_table = 'instagram_account'
unique_together = (('account_id_account', 'username'),)
class Proxy(models.Model):
id_proxy = models.AutoField(primary_key=True)
proxy = models.CharField(max_length=45, blank=False, null=False)
meta = models.TextField(null=True)
start_date = models.DateTimeField(null=False)
end_date = models.DateTimeField(null=True)
country = models.CharField(max_length=45, null=False)
period = models.PositiveIntegerField()
price = models.FloatField(validators=[MinValueValidator(0.0), ])
# It can confuse, but our proxy provider have it own id for proxy
proxy_provider_id = models.PositiveIntegerField()
ip = models.CharField(max_length=45, null=False, blank=False)
account = models.ForeignKey(InstagramAccount, models.DO_NOTHING,
db_column='instagram_account_account_id_account')
class Meta:
managed = False
db_table = 'proxy'
unique_together = (('id_proxy', 'account'),)
如果我使用原始 SQL 查询会更好吗?
【问题讨论】:
【参考方案1】:您在设置prx.country
的行的末尾有一个逗号,这会将其转换为一个元组。
这段代码中有很多奇怪的东西。最重要的是,你真的不应该只为了引发自己的异常而捕获所有异常;你应该抓住你知道你可以处理的错误(并实际处理它们,而不是引发另一个错误);其他一切都应该让 Django 自己处理。
【讨论】:
span class="comcopy">same sh...t,简单的错字,找问题 2 小时...以上是关于Django 保存到 DB:TypeError:int() 参数必须是字符串、类似字节的对象或数字,而不是“元组”的主要内容,如果未能解决你的问题,请参考以下文章
ExpressJS:TypeError:无法读取未定义的属性“路径”尝试将文件上传到 cloudinary 并将 url 保存到 mongoDB
Django App TypeError django.views.i18n.javascript_catalog
Node js & mongoDB - TypeError: db.collection is not a function
/writeReview/1 __str__ 处的 Django 模型 TypeError 返回非字符串(int 类型)