Quy Tang
Quy Tang

Reputation: 3979

Django update fields base on the current fields values

Given the schema:

stats {
  id: integer
  total: integer
  total_accepted: integer
  total_rejecged: integer
}

I need to update the record at one go like this:

UPDATE stats SET total = total + 1, total_accepted = total_accepted + 1 WHERE id=1

So how to achieve it in Django without using a raw sql?

Upvotes: 0

Views: 72

Answers (1)

Clément Denoix
Clément Denoix

Reputation: 1514

What you need is the query expressions:

So using the query expressions (F() method) your query will look like this:

Stats.objects.filter(id=1).update(total=F('total') + 1, total_accepted=F('total_accepted') + 1)

Upvotes: 1

Related Questions