简体   繁体   English

Python/Django 模型字典允许一种类型的更新,但不允许另一种类型的更新

[英]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.

相关问题 保存另一个模型后自动更新一个模型的字段[Django 1.11] [Python3.x] - Automatically update a field on one model after saving another [Django 1.11][Python3.x] Python,将字符串转换为字典列表,将一个字典插入Django模型 - Python, Convert String Into List of Dictionaries, Insert One Dictionary Into Django Model Django 模型作为 Python 字典键 - Django Model as Python dictionary key Python (DJango) - 同时更新多于一行的模型 - Python (DJango) - Update more than one row of a model simultaneously Django更新根据模型构建的字典中的值 - Django Update values in a dictionary built from a model 从一个模型获取数据到另一个Django / Python - Get data from one model to another Django/Python 如何将 model 字段中的值更新为 Django 中另一个 model 字段的值? - How to update the value from one model field in to value of another model field in Django? Django模型表单,与另一个模型的一对一字段,更新两个模型中的字段 - Django Model Form, One-to-OneField with another model, update fields in both models 在一个字段的更新时自动更改Django模型字段,而对另一字段冻结一次只写操作? - Automatically changing Django model field on update for one field and freezing one-time write-only for another? django 用另一个模型过滤一个模型 - django filter one model with another model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM