Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a dictionary to update fields in Django models?

Suppose I have a model like this:

class Book(models.Model):     num_pages = ...     author = ...     date = ... 

Can I create a dictionary, and then insert or update the model using it?

d = {"num_pages":40, author:"Jack", date:"3324"} 
like image 632
TIMEX Avatar asked Mar 31 '11 17:03

TIMEX


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 does update or create work in Django?

If the object's primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object's primary key attribute is not set or if the UPDATE didn't update anything, Django executes an INSERT.

How do you add fields to a model?

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.


2 Answers

Here's an example of create using your dictionary d:

Book.objects.create(**d) 

To update an existing model, you will need to use the QuerySet filter method. Assuming you know the pk of the Book you want to update:

Book.objects.filter(pk=pk).update(**d) 
like image 132
Thierry Lam Avatar answered Oct 21 '22 17:10

Thierry Lam


Use ** for creating a new model. Loop through the dictionary and use setattr() in order to update an existing model.

From Tom Christie's Django Rest Framework

https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py

for attr, value in validated_data.items():     setattr(instance, attr, value) instance.save() 
like image 25
Ignacio Vazquez-Abrams Avatar answered Oct 21 '22 18:10

Ignacio Vazquez-Abrams