尝试在 django 模型中设置 BooleanField 值时出现奇怪的问题
我正在尝试更改我的模型之一中 BooleanField 的值,但 Django 不允许我这样做。这是相关的代码:
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
不坚持吗?提前致谢!
编辑:这修复了它:
query = MyModel.objects.get(name='example', boolField=False)
query.boolField = True
query.save()
似乎您无法更改过滤所依据的查询中的字段?
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
This surprisingly prints:
False
False
Any idea why the = True
isn't sticking? Thanks in advance!
Edit: This fixed it:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题不在于过滤,而在于切片。每次对查询集进行切片时,Django 都会为您提供一个不同对象:
这里
f
和ff
引用相同的底层数据库行,但实际情况不同对象实例。因此,在您的示例中,您设置布尔值的实例与您尝试保存的实例不同。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:
Here
f
andff
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.