我可以使用Django F()对象与字符串连接吗? [英] Can I use Django F() objects with string concatenation?

查看:776
本文介绍了我可以使用Django F()对象与字符串连接吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过ORM运行一个django更新,看起来像这样:

I want to run a django update through the ORM that looks something like this:

MyModel.objects.filter(**kwargs).update(my_field=F('my_other_field')+'a string')

导致MySQL抛出异常。有没有这样做,而不是编写原始的SQL?

This causes MySQL to throw an exception. Is there anyway to do this without writing raw SQL?

推荐答案

发生什么是Django将'+'传递给SQL - 但是SQL不允许使用'+'进行连接,所以它试图添加数字。如果使用一个整数代替'一个字符串',它的作用就是将 my_other_field 的整数值添加到变量中。

What's happening is that Django is passing the '+' through to SQL - but SQL doesn't allow the use of '+' for concatenation, so it tries to add numerically. If you use an integer in place of 'a string', it does work in the sense that it adds the integer value of my_other_field to your variable.

这是否是一个错误是有争议的。 F()对象查找查询状态:

It's debatable whether this is a bug. The documentation for F() objects in lookup queries states:


Django支持使用加法,减法,乘法,除法模块算术与 F()对象

所以可以说是你不应该尝试使用它来更新字符串。但是这当然没有记录,错误消息DOUBLE值不正确不是很有帮助。我会打开一张票。

so it could be argued that you shouldn't be trying to use it to update with strings. But that's certainly not documented, and the error message 'Incorrect DOUBLE value' is not very helpful. I'll open a ticket.

这篇关于我可以使用Django F()对象与字符串连接吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆