Explore the World's Best Ideas
Join today and uncover 100+ curated journeys from 50+ topics. Unlock access to our mobile app with extensive features.
The ".save()" method is used to write a model instance to the database. It can be an existing record or even a new one. For an existing record, Django will run a SQL UPDATE statement on the database. For a new record, Django will run an INSERT.
2
131 reads
When updating an existing record, Django will update every field. That means, if you changed only one field on the model instance, all the fields will be updated (with the values staying the same). This is inefficient, especially if the model has many fields.
Another problem is that if there's a significant amount of time in between the fetching of the record and the saving of it, it is possible that another request will have updated one of the fields on that record, and your model instance still has the old value.
Calling ".save()" now will overwrite the new value that someone else saved.
2
22 reads
To prevent updating every field of the model you can use the update_fields parameter. It expects a list of fields that you want to save. The UPDATE that is run against the database then only updates those fields that you have specified.
For example, in case we only want to update the price of a toy, we would run "toy.save(update_fields=["price"])".
2
28 reads
2
15 reads
The ".update()" method is available on each queryset object of the ORM. For example, "Toy.objects.filter(price__lt=50).update(price=50)".
This would update the price of all toys that are below a certain price. While this is for a range of records, it could also be used to update a single record: "Toy.objects.filter(name="hippo").update(price=120)".
2
13 reads
2
14 reads
IDEAS CURATED BY
Learn more about artificialintelligence with this collection
Find out the challenges it poses
Learn about the potential impact on society
Understanding the concept of Metaverse
Related collections
Similar ideas
1 idea
Foreign Key on Models | Django documentation
docs.djangoproject.com
2 ideas
PostgreSQL - How to Configure Slow Query Log
postgresql.org
5 ideas
Sanic and Data Validation using Pydantic
python.plainenglish.io
Read & Learn
20x Faster
without
deepstash
with
deepstash
with
deepstash
Personalized microlearning
—
100+ Learning Journeys
—
Access to 200,000+ ideas
—
Access to the mobile app
—
Unlimited idea saving
—
—
Unlimited history
—
—
Unlimited listening to ideas
—
—
Downloading & offline access
—
—
Supercharge your mind with one idea per day
Enter your email and spend 1 minute every day to learn something new.
I agree to receive email updates