[英]Python/Django model dictionary allows one type of update, but not another
I am working on some Django/Python code.我正在处理一些 Django/Python 代码。
Basically, the backend of my code gets sent a dict of parameters named 'p'.基本上,我的代码的后端会发送一个名为“p”的参数字典。 These values all come off Django models.
这些值都来自 Django 模型。
When I tried to override them as such:当我试图像这样覆盖它们时:
p['age']=25
I got a 'model error'.我收到了“模型错误”。 Yet, if I write:
然而,如果我写:
p.age=25
it works fine.它工作正常。
My suspicion is that, internally, choice #1 tries to set a new value to an instance of a class created by Django that objects to being overridden, but internally Python3 simply replaces the Django instance with a "new" attribute of the same name ('age'), without regard for the prior origin, type, or class of what Django created.我的怀疑是,在内部,选择 #1 试图为由 Django 创建的类的实例设置一个新值,该类的对象是被覆盖的,但在内部 Python3 只是用同名的“新”属性替换了 Django 实例( 'age'),而不考虑 Django 创建的先前的起源、类型或类。
All of this is in a RESTful framework, and actually in test code.所有这些都在 RESTful 框架中,实际上在测试代码中。 So even if I am right I don't believe it changes anything for me in reality.
所以即使我是对的,我也不相信它在现实中对我有任何改变。
But can anyone explain why one type of assignment to an existing dict works, and the other fails?但是谁能解释为什么对现有字典的一种赋值有效,而另一种失败?
p is a class, not a dict. p 是一个类,而不是一个字典。 Django built it that way.
Django 就是这样构建的。
But, as such, one approach (p.age) lets you change an attribute of the object in the class.但是,因此,一种方法 (p.age) 允许您更改类中对象的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.