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"}
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.
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.
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.
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)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With