1

Is it possible to update multiple objects with on db call, but setting each selected item to a different value?

I know it can be done with the same value

my_articles = models.Article.objects.filter(...)
for article in my_articles:
    article.name = 'foo'
    article.save()

# is equivalent to
models.Article.objects.filter(...).update(name='foo')

But what if I want to do something like this?

my_articles = models.Article.objects.filter(...)
for article in my_articles:
    article.name = get_new_name_for_this_one_article(article)
    article.save()

# is equivalent to
???

Im using the mysql backend if that matters at all

AlanSTACK
  • 5,525
  • 3
  • 40
  • 99
  • There is no such way. You have to iterate. – Mohammad Mustaqeem Mar 24 '17 at 11:20
  • On the contrary. There maybe lots of different ways. But your question isn't clear enough. You need to post concrete code – e4c5 Mar 24 '17 at 11:23
  • What does `get_new_name_for_this_one_article`? – Sardorbek Imomaliev Mar 24 '17 at 11:24
  • @e4c5 it is my impression that the question is clear. I have a similar situation where I wish to update the database based on `request.POST` data, and reduce the number of commits to the database. I know that in sqlalchemy one can modify any number of rows and then commit everything all at once. – Mirac7 Apr 14 '17 at 09:08

0 Answers0