我有一个DB列,该列是某些统计数据的通用类型(定性和定量信息)。
有些值是字符串 - a型,有些值将数字存储为字符串 - 类型B。
我想做的是将B类型投入数字,然后将其添加到它们中,然后施放回弦并存储。
Metadata.objects.filter(key='EVENT', type='COUNT').update(value=CAST(F(CAST('value', IntegerField()) + 1), CharField())
我想做的是避免使用F表达和
在db。
中更新
https://docs.djangoproject.com/en/4.0/ref/ref/models/models/pexpressions/#avoiding-race-conditions-using-f
它在下面的文章中说,可以在DB中进行铸造和更新DB对于mysql
mysql类型casting在更新查询中
我也知道,我们可以在F表达式上很容易地进行算术,因为它支持它,并且我们也可以覆盖add的功能。 在django'f'类型上进行ArthMetic?
如何 我可以实现铸造 - >更新 - >铸造 - >存储在django queryset?
I have a DB column which is generic type for some stats(qualitative and quantitative info).
Some values are string - type A and some values are numbers stored as string - type B.
What i want to do is cast the B types to number then add one to them and cast back to string and store.
Metadata.objects.filter(key='EVENT', type='COUNT').update(value=CAST(F(CAST('value', IntegerField()) + 1), CharField())
What i want to do is avoid race conditions using F expression and
update in DB.
https://docs.djangoproject.com/en/4.0/ref/models/expressions/#avoiding-race-conditions-using-f
It says in below post that casting and updating in db is possible for mysql
Mysql Type Casting in Update Query
I also know we can do arithmetic very easily on F expressions as it supports it and we can override functionality of add as well. How to do arthmetic on Django 'F' types?
How can i achieve Cast -> update -> cast -> store in Django queryset?
发布评论
评论(2)
尝试使用注释如下:
或者可以切换f和cast有效?
我增加了凹痕,有时会找到错误。
另外, doc 说,Cast Cast接受字段名称,不是F-Object。也许根本没有F-Object的工作?
upd:切换回第一个示例,它实际上有效:)
Try using annotation as follows:
Or maybe switching F and CAST works?
I've added indentation, it helps sometimes to find the errors.
Also, doc says, CAST accepts field name, not an F-object. Maybe it works without F-object at all?
UPD: switched back to first example, it actually works :)
我相信 @SOM-1的答案是有益的,但没有通过信息或调试数据证实。我相信假设并不总是正确的。
我调试了这两种情况下形成的mySQL查询
-1-
metadata.objects.update(value = cast(cast(f cast('value'),output_field = integerfield()) + 1,output_field = charfield = charfield()) )
2-
metadata.objects.update(value = cast(cast('value',integerfield()),integerfield()) + 1, charfield()))
和两者都给出与预期的相同输出。
请找到将mysqld选项添加到我的cnf并调试查询的链接。 https .com/blog/2018/10/how-to-show-queries-log-in-mysql.html
I believe the answer from @som-1 was informative but not substantiated with info or debugged data. I believe assuming is not always right.
I debugged the mysql queries formed in these two cases -
1 -
Metadata.objects.update(value=Cast(Cast(F('value'), output_field=IntegerField()) + 1, output_field=CharField()))
2 -
Metadata.objects.update(value=Cast(Cast('value', IntegerField()) + 1, CharField()))
andboth give the same output as expected.
Please find the link to add mysqld options to my.cnf and debug your queries. Location of my.cnf file on macOS
enabling queries - https://tableplus.com/blog/2018/10/how-to-show-queries-log-in-mysql.html