python - Django 将 sqlite3 db 迁移到 postgres 查询整数 : "none" error 的无效输入语法

标签 python django postgresql sqlite

我的项目使用Django 2.0数据库,从sqlite迁移到postgresql 9.6.3,在sqilet中运行正常,迁移到postgresql运行报错。

模型.py:

Class WechatPay(models.Model):
    user = models.CharField('网点', max_length=20, default='None')
    user_group = models.CharField('渠道', max_length=20, default='None')
    total_fee = models.FloatField('订单金额', default=0, decimal_places=0, max_digits=7)
    card_sale = models.FloatField('售卡款', default=0, decimal_places=0, max_digits=7)
    card_recharge = models.FloatField('充值款', default=0, decimal_places=0, max_digits=7)
    trade_date = models.DateField('交易日期', auto_now_add=True)

View .py :

def group_list(request):
    start_time = request.GET.get('start_time', datetime.today().strftime("%Y-%m-%d"))
    end_time = request.GET.get('end_time', datetime.today().strftime("%Y-%m-%d"))
    object_list = WechatPay.objects.values('user', 'trade_date', 'user_group').filter(
    trade_date__gte=start_time).filter(
    trade_date__lte=end_time).filter(
    status='SUCCESS').annotate(
    card_sale=Cast(Sum('card_sale'), DecimalField(decimal_places=2)),
    total_fee=Cast(Sum('total_fee'), DecimalField(decimal_places=2)),
    card_recharge=Cast(Sum('card_recharge'), DecimalField(decimal_places=2))
).order_by('-trade_date')
summary = WechatPay.objects.filter(
    trade_date__gte=start_time).filter(
    trade_date__lte=end_time).filter(
    status='SUCCESS').aggregate(card_sale_sum=Cast(Sum('card_sale'), DecimalField(decimal_places=2)),
                                total_fee_sum=Cast(Sum('total_fee'), DecimalField(decimal_places=2)),
                                card_recharge_sum=Cast(Sum('card_recharge'), DecimalField(decimal_places=2)))
return render(request, 'wechatpay/data-group.html',
              {'items': object_list, 'start_time': start_time, 'end_time': end_time,
               'summary': summary})

错误:

Traceback (most recent call last):
File "D:\workspace\venv\venv-django\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.DataError: invalid input syntax for integer: "none"
LINE 1: ...LECT SUM("gft_wechat_pay_wechatpay"."card_sale")::numeric(No...
                                                             ^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\workspace\venv\venv-django\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "D:\workspace\venv\venv-django\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\workspace\venv\venv-django\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\workspace\venv\venv-django\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "D:\workspace\weixin_pay\gft_web\gft_wechat_pay\views.py", line 249, in group_list
card_recharge_sum=Cast(Sum('card_recharge'), DecimalField(decimal_places=2)))
File "D:\workspace\venv\venv-django\lib\site-packages\django\db\models\query.py", line 374, in aggregate
return query.get_aggregation(self.db, kwargs)
File "D:\workspace\venv\venv-django\lib\site-packages\django\db\models\sql\query.py", line 476, in get_aggregation
result = compiler.execute_sql(SINGLE)
File "D:\workspace\venv\venv-django\lib\site-packages\django\db\models\sql\compiler.py", line 1063, in execute_sql
cursor.execute(sql, params)
File "D:\workspace\venv\venv-django\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "D:\workspace\venv\venv-django\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "D:\workspace\venv\venv-django\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "D:\workspace\venv\venv-django\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "D:\workspace\venv\venv-django\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "D:\workspace\venv\venv-django\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.DataError: invalid input syntax for integer: "none"
LINE 1: ...LECT SUM("gft_wechat_pay_wechatpay"."card_sale")::numeric(No...

查询sql:

SELECT "gft_wechat_pay_wechatpay"."user", "gft_wechat_pay_wechatpay"."trade_date", "gft_wechat_pay_wechatpay"."user_group", SUM("gft_wechat_pay_wechatpay"."card_sale")::numeric(None, 2) AS "card_sale", SUM("gft_wechat_pay_wechatpay"."total_fee")::numeric(None, 2) AS "total_fee", SUM("gft_wechat_pay_wechatpay"."card_recharge")::numeric(None, 2) AS "card_recharge" FROM "gft_wechat_pay_wechatpay" WHERE ("gft_wechat_pay_wechatpay"."trade_date" >= 2018-01-27 AND "gft_wechat_pay_wechatpay"."trade_date" <= 2018-01-27 AND "gft_wechat_pay_wechatpay"."status" = SUCCESS) GROUP BY "gft_wechat_pay_wechatpay"."user", "gft_wechat_pay_wechatpay"."trade_date", "gft_wechat_pay_wechatpay"."user_group" ORDER BY "gft_wechat_pay_wechatpay"."trade_date" DESC

我尝试更改 models.py 字段类型,从 FloatField 到 DecimalField,但 View 保存为零。 模型.py:

Class WechatPay(models.Model):
    user = models.CharField('网点', max_length=20, default='None')
    user_group = models.CharField('渠道', max_length=20, default='None')
    total_fee = models.DecimalField('订单金额', default=0, decimal_places=0, max_digits=7)
    card_sale = models.DecimalField('售卡款', default=0, decimal_places=0, max_digits=7)
    card_recharge = models.DecimalField('充值款', default=0, decimal_places=0, max_digits=7)
    trade_date = models.DateField('交易日期', auto_now_add=True)

views.py:

def qrcode(request, cost):
    """ Insert data """
    trade_log = WechatPay()
    total_fee = int(result[0].get('total_fee')) / 100
    print(f'receive data {total_fee},date type {type(total_fee)}')
    trade_log.total_fee = Decimal(total_fee)
    print(trade_log.total_fee)
    print(type(trade_log.total_fee))
    trade_log.save()

控制台:

receive data 0.21,date type <class 'float'>
0.2099999999999999922284388276239042170345783233642578125
<class 'decimal.Decimal'>

但数据库保存的“total_fee”字段为 0。 请帮忙。提前致谢。

最佳答案

这里的一个潜在问题可能是您如何尝试将 NULL 值存储到数据库中。在 Django/Python 中,您使用 None 传入 NULL 值。当您执行实际的 SQL 语句时,这需要转换为 NULL,Django 应该在幕后处理它。这可能是您出现上述初始语法错误的原因。

如果您克服了语法错误,请尝试更改此行:

total_fee = int(result[0].get('total_fee')) / 100

尝试使用 100.00 而不是 100 并查看更新数据库时它是否保留小数精度。

如果这不起作用,请查看这一行:

total_fee = models.DecimalField('订单金额', default=0, decimal_places=0, max_digits=7)

尝试将 "default=0" 更改为 "default=999"。如果您运行代码并看到设置为 999 的值,则表示没有传入任何值,此时可以开始查找。

关于python - Django 将 sqlite3 db 迁移到 postgres 查询整数 : "none" error 的无效输入语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48487401/

相关文章:

python - Django Userena 更改 url 监护人错误

python - 使用recursion.python求指数和

python - 数据加载器 tqdm 的最佳方式

python - 明智地创建新的数据框条件

主键上的 Django unique_together

python - 时间戳转换关闭一小时

django - manage.py migrate 导致 'staticmethod' 对象不可调用

postgresql - Spring-Boot 不适用于 Flyway

sql - 从 rails 5 获取随机记录,但在顶部保留一条记录(基于某个值)

sql-server - 更新查询在 SQL Server 中按预期工作,但在 Postgresql 中不工作