Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update multiple fields of a django model instance?

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.

like image 540
Purrell Avatar asked Oct 16 '09 07:10

Purrell


People also ask

How do I update model fields in Django?

Use update_fields in save() If you would like to explicitly mention only those columns that you want to be updated, you can do so using the update_fields parameter while calling the save() method. You can also choose to update multiple columns by passing more field names in the update_fields list.

How do you add a new field to a model with new Django migrations?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.

How does many to many field work in Django?

The invisible "through" model that Django uses to make many-to-many relationships work requires the primary keys for the source model and the target model. A primary key doesn't exist until a model instance is saved, so that's why both instances have to exist before they can be related.


1 Answers

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) obj.save() 

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) 
like image 148
Wilfred Hughes Avatar answered Oct 09 '22 15:10

Wilfred Hughes