如何更新django模型实例的多个字段? [英] How to update multiple fields of a django model instance?
问题描述
我想知道,在django中更新模型实例的多个字段的标准方法是什么? ...如果我有一些字段的模型,
类foomodel(models.Model):
field1 = models.CharField(max_length = 10)
field2 = models.CharField(max_length = 10)
field3 = models.CharField(max_length = 10)
...
...我用一个字段给出了实例化,然后在另一个步骤中,我想提供其余的字段,只需传递一个字典或键值参数,我该怎么办?可以吗?
换句话说,说我有一个字典,其中有一些数据,它有我想要写入该模型的一个实例的一切。模型实例已经在一个单独的步骤中被实例化,并且假设它还没有被持久化。我可以为每个字段说 foo_instance.field1 = my_data_dict ['field1']
,但有些东西告诉我应该有一种方法来调用模型实例上的方法,一次传递所有的字段值对,并更新它们。像 foo_instance.update(my_data_dict)
。我没有看到任何这样的内置方法,我错过了,还是有效地完成了?
我有一种感觉这是一个明显的RTM类型的问题,但我没有在文档中看到它。
很有可能混淆 __ dict __
,但这不适用于从父类继承的属性。 / p>
您可以对dict进行迭代,以分配给对象:
for(key,value)in my_data_dict.items():
setattr(obj,key,value)
或者您可以直接从查询集修改它(确保您的查询集仅返回您感兴趣的对象):
code> FooModel.objects.filter(whatever =anything)。update(** my_data_dict)
I'm wondering, what is a standard way of updating multiple fields of an instance of a model in django? ... If I have a model with some fields,
Class foomodel(models.Model):
field1 = models.CharField(max_length=10)
field2 = models.CharField(max_length=10)
field3 = models.CharField(max_length=10)
...
... and I instantiate it with one field given, and then in a separate step I want to provide the rest of the fields, how do I do that by just passing a dictionary or key value params? Possible?
In other words, say I have a dictionary with some data in it that has everything I want to write into an instance of that model. The model instance has been instantiated in a separate step and let's say it hasn't been persisted yet. I can say foo_instance.field1 = my_data_dict['field1']
for each field, but something tells me there should be a way of calling a method on the model instance where I just pass all of the field-value pairs at once and it updates them. Something like foo_instance.update(my_data_dict)
. I don't see any built-in methods like this, am I missing it or how is this efficiently done?
I have a feeling this is an obvious, RTM kind of question but I just haven't seen it in the docs.
It's tempting to mess with __dict__
, but that won't apply to attributes inherited from a parent class.
You can either iterate over the dict to assign to the object:
for (key, value) in my_data_dict.items():
setattr(obj, key, value)
Or you can directly modify it from a queryset (making sure your query set only returns the object you're interested in):
FooModel.objects.filter(whatever="anything").update(**my_data_dict)
这篇关于如何更新django模型实例的多个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!