尝试在django模型中设置BooleanField值时出现奇怪的问题 [英] Strange issue when trying to set a BooleanField value in a django model

查看:604
本文介绍了尝试在django模型中设置BooleanField值时出现奇怪的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的一个模型中更改BooleanField的值,但Django不会让我。以下是相关代码:

I'm trying to change the value of a BooleanField in one of my models, but Django won't let me. Here's the relevant code:

query = MyModel.objects.filter(name='example').filter(boolField=False)
print query[0].boolField
query[0].boolField = True
query[0].save()
print query[0].boolField

这令人惊讶地打印:

False
False

任何想法为什么 = True 不贴吧感谢提前!

Any idea why the = True isn't sticking? Thanks in advance!

编辑:这修正了:

query = MyModel.objects.get(name='example', boolField=False)
query.boolField = True
query.save()

似乎您无法更改过滤的查询中的字段?

It seems you can't change fields in a query that you filtered by?

推荐答案

这不是过滤问题,它是切片。每次切片时,Django都会提供不同的对象:

It's not the filtering that's the problem, it's the slicing. Each time you slice a queryset, Django gives you a different object:

f = MyModel.objects.all()[0]
f.id       # 1
id(f)      # 4326035152
ff = MyModel.objects.all()[0]
ff.id      # 1
id(ff)     # 4326035344

这里 f ff 指的是相同的底层数据库行,但不同的实际对象实例。所以在你的例子中,您设置布尔值的实例与您尝试保存的实例不同。

Here f and ff refer to the same underlying database row, but different actual object instances. So in your example, the instance you set the boolean on is not the same as the instance you tried to save.

这篇关于尝试在django模型中设置BooleanField值时出现奇怪的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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