django中的F()表达式一直给我0 [英] F() expressions in django keeps giving me 0

查看:98
本文介绍了django中的F()表达式一直给我0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将为我的django模型之一更新大约2-3k的记录. 我知道使用update()会有所帮助,但是因为我实际上是在字段中使用相同的值并将其更改为其他值,例如具有对现有字段进行打乱的功能.

I am about to update approx 2-3k of records for one of my django model. I know that using the update() would help but then because I am actually using the same value in the field and change it into something else for example having a function to scrumble the existing field.

我认为有一种叫做F()的东西应该可以帮助我,但是以某种方式,它会将我的值保存为0到字段中.

I figured there is something called F() would should be able to help me out with it but somehow, it keeps saving my values as 0 into the field.

我没有收到任何错误,也不知道该去哪里找

I did not get any error and have no idea where to look into.

这是我阅读的教程 https://docs.djangoproject.com/zh-CN/1.8/ref/models /expressions/

这是我的示例代码,然后才真正对2-3k记录进行批量更新

this is my example code before I really do such batch update for the 2-3k records

# I used the below, gives me 0 when I look at my db
querysets_of_model = Model.objects.filter(id__in[111, 123]).update(name=F('name') + ' testing')

# this gives me 0 too
querysets = Model.objects.filter(id__in[111,123])
querysets.update(name=F('name') + ' testing')

# without using the F(), which of course gives me `testing only` in the name field
qs = Model.objects.filter(id__in[111, 123]).update(name='testing only')

我本来想要做的就是这样

what I originally wanted to do is something like this

qys = Model.objects.filter().update(name=scrumble_fun(F('name')))

scrumble_fun只是对现有值进行加扰,然后返回经过加扰的值并将其保存的函数.

the scrumble_fun is just a function that scrumble the existing value then return the srcumbled values and save it.

但是,当然,在执行此操作之前,我作为前两个示例只是取出两个查询集并进行测试以确保我做对了.但是好像我不是吗? :(

But of course before doing this, I did as the first two example to just take out two queryets and do testing to make sure I am doing it right. But seems like I am not? :(

在此先感谢您的帮助.

P.S.如果可能的话,循环遍历每个查询集然后不是save()的方式.

P.S. Looping through each queryset then save() is not the way I want to do it if that is possible.

推荐答案

这项工作有效吗?

querysets = Model.objects.filter(id__in[111, 123])
querysets.name = F('name') + ' testing'
querysets.save()

这篇关于django中的F()表达式一直给我0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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