I would like to update many model instances at a time in the database.
If I could select all such instances using a single query and have the
*same* new field value across all instances I could write code like:
def reset_choices(question: Question):
Choice.objects.filter(question=question).update(votes=0)
However if I have *different* new field values I don't see an easy way to
perform all the database updates at once:
def update_choices(choice_votes_tuples: List[Tuple[Choice, int]]):
for (choice, votes) in choice_votes_tuples:
choice.votes = votes
choice.save() # 1 query per Choice!
Here's a hard way of performing all database updates at once with raw SQL:
from django.db import connection
def update_choices(choice_votes_tuples: List[Tuple[Choice, int]]):
query = 'UPDATE polls_choice SET votes=%s WHERE id=%s'
values = [(votes, choice.id) for (choice, votes) in choice_votes_tuples]
with connection.cursor() as c:
c.executemany(query, values) # 1 bulk query for all Choices
*Is there an easy way to perform the above kind of update that I don't know
about?*
If there was an easier API, I'd expect it to look something like:
def update_choices(choice_votes_tuples: List[Tuple[Choice, int]]):
for (choice, votes) in choice_votes_tuples:
choice.votes = votes
choices = choice_votes_tuples.keys()
*Choice.objects.bulk_update(choices, fields=['votes'])*
Thanks for taking the time to read my question.
- David
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/23de1530-fa9d-49ca-9c4d-ad3c06bb3b04%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.