ttps://github.com/saxix/django-adminactions
-- This app allows for what is termed "mass updates".
On Thursday, 5 October 2017 05:50:45 UTC+2, David Foster wrote:
On Thursday, 5 October 2017 05:50:45 UTC+2, David Foster wrote:
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 ChoicesIs 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 django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
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/8a46e3fb-2ca1-4672-be9b-ff367755aaf0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment